acemq_amqp.connection

Publishing and consuming, on top of a transport.

This is where the envelope, the codec and the retry policy meet a broker. It is asyncio because a broker client is: every publish is a round trip and every delivery arrives on its own, and a library that hid that behind blocking calls would make one slow queue stall a whole process. acemq_amqp.sync is the blocking API for programs that are not running a loop, and it is built on this one rather than beside it — one implementation of the retry rules, not two.

   1# Copyright 2026 AceMQ.
   2#
   3# Licensed under the Apache License, Version 2.0 (the "License");
   4# you may not use this file except in compliance with the License.
   5# You may obtain a copy of the License at
   6#
   7#     https://www.apache.org/licenses/LICENSE-2.0
   8#
   9# Unless required by applicable law or agreed to in writing, software
  10# distributed under the License is distributed on an "AS IS" BASIS,
  11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12# See the License for the specific language governing permissions and
  13# limitations under the License.
  14
  15"""Publishing and consuming, on top of a transport.
  16
  17This is where the envelope, the codec and the retry policy meet a broker. It is
  18asyncio because a broker client is: every publish is a round trip and every
  19delivery arrives on its own, and a library that hid that behind blocking calls
  20would make one slow queue stall a whole process. :mod:`acemq_amqp.sync` is the
  21blocking API for programs that are not running a loop, and it is built on this
  22one rather than beside it — one implementation of the retry rules, not two.
  23"""
  24
  25from __future__ import annotations
  26
  27import asyncio
  28import inspect
  29import logging
  30import socket
  31import time
  32import uuid
  33from collections.abc import Awaitable, Callable, Iterable, Mapping, Sequence
  34from dataclasses import dataclass
  35from datetime import datetime, timedelta, timezone
  36from typing import TYPE_CHECKING, Any, TypeAlias
  37from urllib.parse import urlsplit
  38
  39from . import naming
  40from .ack import (
  41    OUTCOME_ACKED,
  42    OUTCOME_DEAD_LETTERED,
  43    OUTCOME_IN_PROGRESS,
  44    OUTCOME_PARKED,
  45    OUTCOME_REJECTED,
  46    OUTCOME_RETRIED,
  47    OUTCOME_STOPPED,
  48    Ack,
  49    Action,
  50    FatalError,
  51    Settlement,
  52)
  53from .codec import Codec, JsonCodec
  54from .envelope import Envelope
  55from .errors import AceMQError, PublishError, PublishingPausedError
  56from .interceptors import (
  57    ConsumeContext,
  58    ConsumeInterceptor,
  59    PublishContext,
  60    PublishInterceptor,
  61    consume_chain,
  62    publish_chain,
  63)
  64from .retry import ZERO, RetryPolicy, Wait, no_retry
  65from .security import Security
  66from .telemetry import (
  67    METRIC_CONSUME_ATTEMPTS,
  68    METRIC_CONSUME_DURATION,
  69    METRIC_CONSUME_IN_FLIGHT,
  70    METRIC_CONSUME_TOTAL,
  71    METRIC_DEAD_LETTERED_TOTAL,
  72    METRIC_PUBLISH_DURATION,
  73    METRIC_PUBLISH_TOTAL,
  74    METRIC_RETRIED_TOTAL,
  75    METRIC_RUNG_MISSING,
  76    METRIC_SET_ASIDE_FAILED,
  77    OUTCOME_CONFIRMED,
  78    OUTCOME_FAILED,
  79    OUTCOME_REFUSED,
  80    OUTCOME_UNROUTABLE,
  81    TAG_EXCHANGE,
  82    TAG_OUTCOME,
  83    TAG_QUEUE,
  84    TAG_ROUTING_KEY,
  85    TAG_TARGET,
  86    HealthReport,
  87    HealthStatus,
  88    NullObserver,
  89    Observer,
  90)
  91from .topology import Topology, declare_where_failures_go
  92
  93if TYPE_CHECKING:
  94    from .patterns.routingslip import PipelineBuilder
  95from .transport import (
  96    BlockedState,
  97    ConsumeSpec,
  98    Delivery,
  99    MessageSource,
 100    Outbound,
 101    PublishResult,
 102    QueueAdmin,
 103    QueueSpec,
 104    Subscription,
 105    Transport,
 106)
 107
 108log = logging.getLogger("acemq")
 109
 110#: How many unacknowledged messages a consumer holds unless it says otherwise.
 111#: Enough that a handler is never waiting on the network, small enough that a
 112#: consumer that stalls does not take a queue's worth of work down with it.
 113DEFAULT_PREFETCH = 20
 114
 115#: How many publishes may be waiting for the broker at once, unless a connection
 116#: says otherwise.
 117#:
 118#: Java's ``maxOutstandingPublishes`` and .NET's ``MaxOutstandingPublishes``
 119#: default to the same thousand, and the number is the same one for the same
 120#: reason: enough to keep a broker busy, small enough that the memory it can cost
 121#: is bounded and obvious. A publisher that wants more should say so rather than
 122#: inherit it.
 123DEFAULT_MAX_OUTSTANDING_PUBLISHES = 1000
 124
 125#: How long a publish waits for room when every permit is taken, unless a
 126#: connection says otherwise. Java's ``confirmTimeout``, and the same ten seconds.
 127DEFAULT_CONFIRM_TIMEOUT = timedelta(seconds=10)
 128
 129#: How long :meth:`Connection.health` gives the broker to answer its probe.
 130#:
 131#: Shorter than the five seconds :func:`~acemq_amqp.telemetry.aggregate_health`
 132#: gives a whole set of checks, and deliberately: the connection's own answer for
 133#: a broker that has stopped answering is the careful one — up when the broker
 134#: has blocked this connection, down when it has simply gone — and an aggregate
 135#: whose deadline expired first would replace it with a flat "did not answer
 136#: within 5s". The inner deadline has to run out first for the outer one to have
 137#: anything to report.
 138DEFAULT_HEALTH_TIMEOUT = 3.0
 139
 140#: How long, in seconds, closing waits for handlers that are already running
 141#: before it stops waiting. Twenty, which is the figure Java, .NET and Ruby use:
 142#: long enough for an ordinary handler to finish, and inside the thirty seconds
 143#: an orchestrator usually allows between asking a process to stop and killing
 144#: it, so the connection is closed cleanly rather than torn down from outside.
 145DEFAULT_DRAIN_TIMEOUT = 20.0
 146
 147# ponytail: a fixed pause gives about twenty seconds of refusal before a quorum
 148# source queue's delivery limit; a backoff that grows per message if that is short.
 149#: How long, in seconds, a delivery whose dead letter or park the broker refused
 150#: is held before it is requeued. Not at once: the message comes straight back,
 151#: is refused again, and the loop runs at broker speed — and a quorum queue
 152#: counts every requeue against its delivery limit (twenty by default on
 153#: RabbitMQ 4), after which the broker dead-letters the message itself.
 154SET_ASIDE_REFUSED_DELAY = 1.0
 155
 156#: What a health report says about a connection the broker has blocked. It is
 157#: reported **up**, which is the one place this disagrees with a naive reading of
 158#: the state: a blocked connection is the broker protecting itself from a disk or
 159#: memory alarm, and an application that fails its own readiness check for it is
 160#: one an orchestrator restarts into the same blocked broker, having thrown away
 161#: whatever it was holding. Java's ``AceMqHealthIndicator`` and Go's health check
 162#: make the same call for the same reason.
 163#:
 164#: **This is a fixed prefix, and it is the same sentence in every AceMQ
 165#: library** — Go's ``blockedPrefix`` and Ruby's ``Health::BLOCKED`` are these
 166#: exact words. An operator writes one alert rule that matches a blocked broker
 167#: whatever language the service is in, so the wording is a contract rather than
 168#: a phrasing. Anything the broker itself said is appended after a colon; this
 169#: library cannot recover that reason (see :attr:`Connection.blocked_reason`),
 170#: so on RabbitMQ the detail is the prefix alone.
 171#:
 172#: The reasoning above belongs in the documentation, not in the line somebody
 173#: reads at three in the morning, which is why it is a comment here and not part
 174#: of the string.
 175BLOCKED_DETAIL = "the broker has blocked this connection; publishing is paused"
 176
 177
 178@dataclass(frozen=True, slots=True)
 179class Message:
 180    """A delivery that has been decoded.
 181
 182    :param payload: the body, read through the codec
 183    :param envelope: the metadata that travelled with it
 184    :param routing_key: the key it arrived under
 185    :param content_type: what the sender said the body was, or ``None``
 186    :param redelivered: the broker saying it has handed this one over before
 187    :param body: the undecoded bytes, for a handler that wants to see them
 188    :param reply_to: AMQP's own ``reply-to`` property, empty when the sender set
 189        none. A responder reads it as the fallback behind the
 190        ``acemq-reply-to`` header, which is what lets a Java or .NET caller —
 191        neither of which writes the header — be answered by a Python responder
 192    """
 193
 194    payload: Any
 195    envelope: Envelope
 196    routing_key: str
 197    content_type: str | None
 198    redelivered: bool
 199    body: bytes
 200    reply_to: str = ""
 201
 202
 203#: What a handler is. Returning an :class:`~acemq_amqp.Ack` is the decision.
 204#:
 205#: Both shapes are accepted because both are honest: a handler that talks to a
 206#: database over asyncio is a coroutine, and a handler that only does arithmetic
 207#: should not have to pretend to be one.
 208Handler: TypeAlias = Callable[[Message], "Ack | Awaitable[Ack]"]
 209
 210#: A handler that is definitely a coroutine function, which every handler
 211#: :mod:`acemq_amqp.patterns` builds is.
 212#:
 213#: It is a :data:`Handler` and can be passed anywhere one can. The narrower name
 214#: exists so that a caller who wants to run a wrapped handler directly — a test,
 215#: usually — can await it without mypy pointing out that the wider type might not
 216#: be awaitable.
 217AsyncHandler: TypeAlias = Callable[[Message], Awaitable[Ack]]
 218
 219
 220class Publisher:
 221    """Sends messages to one destination.
 222
 223    Cheap to keep and safe to share: build one per message type at start-up
 224    rather than one per message.
 225    """
 226
 227    def __init__(
 228        self,
 229        connection: Connection,
 230        exchange: str,
 231        routing_key: str,
 232        *,
 233        codec: Codec | None = None,
 234        persistent: bool = True,
 235        mandatory: bool = True,
 236    ) -> None:
 237        self._connection = connection
 238        self._exchange = exchange
 239        self._routing_key = routing_key
 240        self._codec = codec or connection.codec
 241        self._persistent = persistent
 242        self._mandatory = mandatory
 243
 244    async def send(
 245        self,
 246        payload: Any,
 247        *,
 248        envelope: Envelope | None = None,
 249        routing_key: str | None = None,
 250        reply_to: str = "",
 251    ) -> PublishResult:
 252        """Publishes one message.
 253
 254        The envelope is built here when none is given: an identifier, a
 255        correlation defaulting to it, this connection's origin, and now. The
 256        type falls back to the routing key, which is why a publisher bound to
 257        ``order.placed`` needs no further configuration to say what it sends.
 258
 259        :param payload: what to send, encoded by this publisher's codec
 260        :param envelope: metadata to send instead of a fresh one, for a message
 261            derived from another
 262        :param routing_key: what to publish under, for a publisher bound to an
 263            exchange rather than to one key
 264        :param reply_to: where an answer should come back to, written to AMQP's
 265            own ``reply-to`` property. Only :mod:`~acemq_amqp.patterns` request
 266            and reply sets it, and it sets the ``acemq-reply-to`` header to the
 267            same value: the header is what survives a service that rebuilds the
 268            message, the property is what the other four libraries read
 269        :returns: what the broker said
 270        :raises PublishError: when the publisher is mandatory — the default — and
 271            the message reached no queue; its ``unroutable`` is true
 272        """
 273        key = self._routing_key if routing_key is None else routing_key
 274        outgoing = envelope or Envelope(origin=self._connection.origin)
 275        if not outgoing.origin:
 276            # A message derived from another — a reply, a pipeline hop, the next
 277            # stop on a routing slip — is still published by this process, and an
 278            # origin naming the service before it would be a lie in a log line
 279            # somebody is going to trust.
 280            outgoing = outgoing.with_(origin=self._connection.origin)
 281
 282        context = PublishContext(
 283            exchange=self._exchange,
 284            routing_key=key,
 285            envelope=outgoing,
 286            payload=payload,
 287            persistent=self._persistent,
 288            mandatory=self._mandatory,
 289            reply_to=reply_to,
 290        )
 291        # Read here rather than at construction, so an interceptor registered
 292        # during start-up applies to the publishers that already exist. Building
 293        # the chain per message costs a few closures and buys that.
 294        return await publish_chain(self._connection.publish_interceptors, self._send)(context)
 295
 296    async def send_all(self, payloads: Iterable[Any]) -> list[PublishResult]:
 297        """Publishes a batch and waits for every confirm.
 298
 299        What most bulk publishing actually wants: the throughput of pipelining
 300        with the safety of having waited. Every message goes out before any
 301        confirm is awaited, and only then are all of them checked together.
 302        Awaiting each send in turn is a broker round trip per message — the
 303        loop a caller could have written for themselves, and none of the
 304        throughput a batch exists for.
 305
 306        The results come back in the order the payloads were given, whatever
 307        order the broker answers in.
 308
 309        **This is not atomic.** AMQP has no such thing: there is no way to
 310        publish a hundred messages such that all or none arrive, and a library
 311        that offered one would be lying. A failure does not abandon the rest
 312        either — every send is awaited whatever an earlier one did, so a batch
 313        that half succeeded can say how many arrived. That count is the point:
 314        a caller told only "it failed" resends the messages the broker already
 315        has.
 316
 317        How wide the batch gets on the wire is capped, and by the connection
 318        rather than by this method:
 319        :attr:`Connection.max_outstanding_publishes` is a thousand by default,
 320        and the thousand-and-first task waits for one of the first thousand to
 321        be answered before its message is written. A list of a million is
 322        therefore a million tasks and a thousand messages in flight rather than
 323        a million, which is backpressure instead of a memory leak — but a
 324        million tasks is still a million tasks, so chunk what comes out of a
 325        database rather than handing a cursor's worth of rows to one call.
 326
 327        :param payloads: what to send, in order, each encoded by this
 328            publisher's codec
 329        :returns: what the broker said about each, in the order the payloads
 330            were given
 331        :raises PublishError: when any message was not confirmed. Its message
 332            names how many failed and how many did not, and ``__cause__``
 333            carries the first failure in payload order — which is not
 334            necessarily the first one the broker answered. A batch wide enough
 335            that the broker stops keeping up fails this way too, with the first
 336            failure saying so
 337        """
 338        batch = list(payloads)
 339        # Everything is started before anything is awaited. A task per payload,
 340        # all of them created before the gather below, is what puts the whole
 341        # batch on the wire while the broker is still working through the
 342        # first confirm.
 343        sends = [asyncio.create_task(self.send(payload)) for payload in batch]
 344        # return_exceptions, and not for tidiness: without it the first failure
 345        # comes out of the gather while the rest of the batch is still in
 346        # flight, which loses the count this method exists to report and leaves
 347        # the others' exceptions unretrieved for asyncio to complain about
 348        # later.
 349        settled = await asyncio.gather(*sends, return_exceptions=True)
 350
 351        results: list[PublishResult] = []
 352        first_failure: BaseException | None = None
 353        failed = 0
 354        for outcome in settled:
 355            if isinstance(outcome, BaseException):
 356                failed += 1
 357                if first_failure is None:
 358                    first_failure = outcome
 359            else:
 360                results.append(outcome)
 361
 362        if first_failure is not None:
 363            # Named rather than printed. A failure with nothing in its message —
 364            # the CancelledError every task gets when the connection closes
 365            # underneath the batch is the common one — renders as an empty
 366            # string, and the sentence then ends "The first failure was: " and
 367            # stops, promising an explanation it does not give. The class name
 368            # is not much, but it is the difference between "the sends were
 369            # cancelled" and nothing at all.
 370            described = str(first_failure) or type(first_failure).__name__
 371            # The counts matter. A batch that half succeeded is the ordinary
 372            # outcome of a broker problem partway through, and this sentence is
 373            # word for word the one Java and .NET raise, so that an operator
 374            # reading a log has one thing to recognise rather than three.
 375            raise PublishError(
 376                "",
 377                self._exchange,
 378                self._routing_key,
 379                described,
 380                summary=(
 381                    f"{failed} of {len(batch)} messages were not confirmed;"
 382                    f" {len(results)} were. The first failure was: {described}"
 383                ),
 384            ) from first_failure
 385        return results
 386
 387    async def _send(self, context: PublishContext) -> PublishResult:
 388        """The innermost work: encode what the interceptors left, and send it."""
 389        observer = self._connection.observer
 390        # ``routing.key`` and not ``key``: Java and .NET both tag a publish with
 391        # the fully-qualified name, and a dashboard that groups by it should
 392        # read the same in all five languages.
 393        labels = {TAG_EXCHANGE: context.exchange, TAG_ROUTING_KEY: context.routing_key}
 394        # Started before the encode, because everything from here on is time the
 395        # caller spends inside send(): the codec, the wait for a permit and the
 396        # broker's confirm are all things that make a publish slow, and a timer
 397        # that began after the encode would hide a slow codec completely.
 398        started = time.monotonic()
 399
 400        def record(outcome: str) -> None:
 401            """The pair, always together and always with the same labels.
 402
 403            Two calls rather than one because the interface has two methods, and
 404            in this order because a dashboard dividing the duration's count into
 405            the total should never see the total lead it.
 406            """
 407            observer.observe(
 408                METRIC_PUBLISH_DURATION,
 409                time.monotonic() - started,
 410                {**labels, TAG_OUTCOME: outcome},
 411            )
 412            observer.count(METRIC_PUBLISH_TOTAL, 1, {**labels, TAG_OUTCOME: outcome})
 413
 414        # Encoded here rather than before the chain ran, so an interceptor can
 415        # change the payload as well as its metadata. A codec that has already
 416        # run leaves an interceptor with bytes and nothing it can do to them.
 417        try:
 418            body = self._codec.encode(context.payload)
 419            result = await self._connection.publish_raw(
 420                context.exchange,
 421                context.routing_key,
 422                Outbound(
 423                    body=body,
 424                    content_type=self._codec.content_type,
 425                    message_id=context.envelope.id,
 426                    reply_to=context.reply_to,
 427                    headers=context.envelope.to_headers(routing_key=context.routing_key),
 428                    persistent=context.persistent,
 429                    mandatory=context.mandatory,
 430                ),
 431            )
 432        except PublishingPausedError:
 433            # Declined before anything was written: nothing lost, so not
 434            # ``failed``, which is the outcome an alert on loss watches.
 435            record(OUTCOME_REFUSED)
 436            raise
 437        except Exception:
 438            record(OUTCOME_FAILED)
 439            raise
 440
 441        # Raised rather than left in the result, because a caller who does not
 442        # read the result would otherwise carry on believing the message went
 443        # somewhere. Unroutable is the quietest failure AMQP has: the publish
 444        # succeeds, the consumer waits, and nothing anywhere says why.
 445        if context.mandatory and not result.routed:
 446            record(OUTCOME_UNROUTABLE)
 447            raise PublishError(
 448                context.envelope.id,
 449                context.exchange,
 450                context.routing_key,
 451                result.return_reason or "no queue is bound to receive it",
 452                unroutable=True,
 453            )
 454
 455        record(OUTCOME_CONFIRMED)
 456        return result
 457
 458
 459class _HopRefusedError(Exception):
 460    """The broker refused a republish the consumer made on the user's behalf."""
 461
 462
 463class _StopReadingError(Exception):
 464    """Raised by a handler wrapper to stop its consumer at this delivery.
 465
 466    What a stream reader does when its handler fails (AceMQ TCK requirement
 467    AMQP-STREAM-004): the delivery is neither retried nor set aside, the
 468    subscription is closed, and every delivery already prefetched is returned
 469    unhandled. Private, because only :func:`acemq_amqp.patterns.read_stream`
 470    has a use for it: on a queue, stopping at a message hands it to the next
 471    consumer, which is a retry with extra steps.
 472    """
 473
 474
 475class Consumer:
 476    """A running subscription. Close it to stop.
 477
 478    One is built by :meth:`Connection.consume` rather than directly, because it
 479    has to be started before it is any use and a half-built consumer that looks
 480    finished is a thing somebody will hold on to.
 481
 482    Starting one declares the queues it will need when a message fails — its
 483    dead-letter queue, its parking lot and its rungs — unless it was told not
 484    to. See :func:`acemq_amqp.topology.declare_where_failures_go`.
 485    """
 486
 487    def __init__(
 488        self,
 489        connection: Connection,
 490        queue: str,
 491        handler: Handler,
 492        *,
 493        codec: Codec,
 494        retry: RetryPolicy,
 495        concurrency: int,
 496        declare: bool = True,
 497    ) -> None:
 498        if concurrency < 1:
 499            raise ValueError(f"acemq: concurrency must be at least 1, got {concurrency}")
 500        self._connection = connection
 501        self._queue = queue
 502        self._handler = handler
 503        self._codec = codec
 504        self._retry = retry
 505        self._concurrency = concurrency
 506        self._declare = declare
 507        self._work: asyncio.Queue[Delivery | None] = asyncio.Queue()
 508        self._workers: list[asyncio.Task[None]] = []
 509        self._subscription: Subscription | None = None
 510        self._in_flight = 0
 511        self._closed = False
 512        self._halted = False
 513        self._halting: asyncio.Task[bool] | None = None
 514
 515    @property
 516    def queue(self) -> str:
 517        """The queue this consumer reads."""
 518        return self._queue
 519
 520    @property
 521    def closed(self) -> bool:
 522        """Whether this consumer has been stopped."""
 523        return self._closed
 524
 525    @property
 526    def running(self) -> bool:
 527        """Whether this consumer is subscribed and still has workers to hand a
 528        delivery to.
 529
 530        What a health check reads. A consumer whose workers have all finished
 531        without it being closed is a consumer the broker is still sending
 532        messages to and nothing is reading — which looks identical to a quiet
 533        queue from outside, and is the failure worth telling a probe about.
 534        """
 535        return (
 536            not self._closed
 537            and self._subscription is not None
 538            and any(not worker.done() for worker in self._workers)
 539        )
 540
 541    @property
 542    def in_flight(self) -> int:
 543        """How many messages this consumer is working on right now."""
 544        return self._in_flight
 545
 546    @property
 547    def _labels(self) -> dict[str, str]:
 548        return {TAG_QUEUE: self._queue}
 549
 550    @property
 551    def _observer(self) -> Observer:
 552        return self._connection.observer
 553
 554    async def _start(self, prefetch: int, tag: str, args: Mapping[str, Any]) -> None:
 555        if self._declare:
 556            # Before the subscription rather than after it, so that the first
 557            # message this consumer gives up on already has somewhere to go. A
 558            # broker that refuses one of these declarations is a consumer that
 559            # does not start, which is the honest failure: it would otherwise
 560            # start and lose its first dead letter.
 561            await declare_where_failures_go(
 562                self._connection.transport, self._queue, self._retry
 563            )
 564
 565        self._workers = [
 566            asyncio.create_task(self._work_loop(), name=f"acemq-consumer-{self._queue}-{n}")
 567            for n in range(self._concurrency)
 568        ]
 569        try:
 570            self._subscription = await self._connection.transport.consume(
 571                self._queue,
 572                ConsumeSpec(prefetch=prefetch, tag=tag, args=dict(args)),
 573                self._deliver,
 574            )
 575        except BaseException:
 576            # Nothing was subscribed, so nothing will arrive; the workers would
 577            # otherwise sit on an empty queue for the life of the process.
 578            for _ in self._workers:
 579                self._work.put_nowait(None)
 580            await asyncio.gather(*self._workers)
 581            raise
 582
 583    async def _deliver(self, delivery: Delivery) -> None:
 584        """Hands a delivery to the workers.
 585
 586        Queued rather than handled here, so that ``concurrency`` means what it
 587        says: aio-pika starts a task per delivery and does not wait for the last
 588        one, so without a queue of our own a prefetch of twenty would run twenty
 589        handlers at once whatever the caller asked for. The queue needs no bound
 590        because prefetch is one: the broker will not send a twenty-first message
 591        until one of the twenty has been settled.
 592        """
 593        self._work.put_nowait(delivery)
 594
 595    async def _work_loop(self) -> None:
 596        while True:
 597            delivery = await self._work.get()
 598            if delivery is None:
 599                return
 600            try:
 601                await self._handle(delivery)
 602            except Exception:
 603                # A failure here is this library's, not the handler's, and the
 604                # message is left unsettled on purpose: the broker will hand it
 605                # back rather than it disappearing because our own code broke.
 606                log.exception("acemq: could not settle a delivery from %s", self._queue)
 607
 608    async def _handle(self, delivery: Delivery) -> None:
 609        envelope = Envelope.from_headers(
 610            delivery.headers, delivery.routing_key, delivery.message_id
 611        )
 612        # No counter for "a message arrived": every delivery is counted once
 613        # when it is settled, on ``acemq.consume.total`` with the outcome, and
 614        # the sum across the outcomes is how many arrived. One counter that
 615        # leads the others by however many messages are in flight is a counter
 616        # that makes an operator wonder which one is lying.
 617        #
 618        # The attempt is a distribution rather than a counter, and it is recorded
 619        # here on arrival rather than at the settlement: it is a fact about the
 620        # delivery that is true before the handler runs, and recording it after
 621        # would drop every message this consumer is still working on when the
 622        # process stops. A rising distribution is a dependency in trouble, and it
 623        # says so before anything else does — the dead letters only move once the
 624        # attempts run out.
 625        self._observer.observe(
 626            METRIC_CONSUME_ATTEMPTS, float(envelope.attempt), self._labels
 627        )
 628        self._in_flight += 1
 629        self._observer.gauge(METRIC_CONSUME_IN_FLIGHT, self._in_flight, self._labels)
 630        try:
 631            await self._handle_one(delivery, envelope)
 632        finally:
 633            self._in_flight -= 1
 634            self._observer.gauge(METRIC_CONSUME_IN_FLIGHT, self._in_flight, self._labels)
 635
 636    async def _handle_one(self, delivery: Delivery, envelope: Envelope) -> None:
 637        if self._halted:
 638            # Prefetched before the reader stopped. Returned unhandled: nothing
 639            # after the message it stopped at is handled.
 640            await delivery.nack(True)
 641            return
 642        try:
 643            payload = self._codec.decode(delivery.body, delivery.content_type)
 644        except Exception as failure:
 645            # A body that will not decode decodes no better next time, so it
 646            # does not go round the retry schedule until it ages out.
 647            #
 648            # Parked rather than dead-lettered: a message that failed five times
 649            # and a message nothing could read are different problems with
 650            # different answers — one is usually the world, the other is usually
 651            # a producer — and whoever drains the dead letters should not have
 652            # to sort them by hand.
 653            #
 654            # Counted as a settled delivery here rather than in ``_carry_out``,
 655            # which this path never reaches: no handler ran, so there is no
 656            # duration to record, but the message did arrive and was dealt with
 657            # and a total that missed it would not add up.
 658            self._observer.count(
 659                METRIC_CONSUME_TOTAL, 1, {**self._labels, TAG_OUTCOME: OUTCOME_PARKED}
 660            )
 661            await self._park(
 662                delivery, envelope, f"could not be decoded: {_describe(failure)}"
 663            )
 664            return
 665
 666        context = ConsumeContext(
 667            queue=self._queue,
 668            envelope=envelope,
 669            payload=payload,
 670            body=delivery.body,
 671            content_type=delivery.content_type,
 672            routing_key=delivery.routing_key,
 673            redelivered=delivery.redelivered,
 674            # This delivery is being driven by a consumer, so how it ends will
 675            # be reported. An interceptor that wants to know can wait for it.
 676            reports_settlement=True,
 677            reply_to=delivery.reply_to,
 678        )
 679
 680        started = time.monotonic()
 681        try:
 682            decision = await consume_chain(
 683                self._connection.consume_interceptors, self._run_handler
 684            )(context)
 685        except Exception as failure:
 686            # An exception is how Python says a thing failed, so a handler that
 687            # raises is asking for the retry policy rather than confessing a
 688            # bug — which is what Java does with the same situation, and what a
 689            # handler written without reading the documentation will expect.
 690            # Raising FatalError is how it says the opposite, and the retry path
 691            # below reads that mark before it reads the request.
 692            #
 693            # An interceptor that raises lands here too, and deliberately: a
 694            # refused message is retried and then dead-lettered rather than
 695            # acknowledged as though something had processed it.
 696            decision = Ack(Action.RETRY, failure)
 697
 698        # Timed around the interceptors as well as the handler, because what an
 699        # operator wants to know is how long a message takes to deal with, and
 700        # an interceptor that opens a transaction is part of dealing with it.
 701        # Stopped here and recorded a few lines below rather than in a
 702        # ``finally``, because the duration is tagged with the outcome and the
 703        # outcome is not known until ``_decide`` has run: how long a message
 704        # took and what happened to it are one question, and a p99 that mixes
 705        # the messages that worked with the ones that timed out answers neither
 706        # half of it.
 707        elapsed = time.monotonic() - started
 708
 709        # Whatever the interceptors left, rather than what arrived: one that
 710        # rewrote the envelope on the way in meant that rewrite for the retry
 711        # and the dead letter as much as for the handler.
 712        envelope = context.envelope
 713
 714        if isinstance(decision, Ack):
 715            settlement, wait = self._decide(envelope, decision)
 716        else:
 717            settlement, wait = (
 718                Settlement(
 719                    OUTCOME_DEAD_LETTERED,
 720                    reason=(
 721                        f"the handler returned {type(decision).__name__} instead of an Ack"
 722                    ),
 723                ),
 724                None,
 725            )
 726
 727        self._observer.observe(
 728            METRIC_CONSUME_DURATION,
 729            elapsed,
 730            {**self._labels, TAG_OUTCOME: settlement.outcome},
 731        )
 732
 733        # Announced before it is carried out, and so before a consumer-side
 734        # retry sleeps out its backoff. A listener told afterwards would be
 735        # describing the delivery minutes after the decision, and the span it is
 736        # writing on would have stayed open for a wait that is not work.
 737        context.settled(settlement)
 738        await self._carry_out(delivery, envelope, settlement, wait)
 739
 740    async def _run_handler(self, context: ConsumeContext) -> Ack:
 741        """The innermost work: build the message the interceptors left, and run
 742        the handler on it.
 743
 744        The message is built here rather than before the chain, so that an
 745        interceptor which changed the envelope or the payload changed what the
 746        handler is given rather than a copy nobody reads.
 747        """
 748        message = Message(
 749            payload=context.payload,
 750            envelope=context.envelope,
 751            routing_key=context.routing_key,
 752            content_type=context.content_type,
 753            redelivered=context.redelivered,
 754            body=context.body,
 755            reply_to=context.reply_to,
 756        )
 757        returned = self._handler(message)
 758        # Not an Ack is a mistake worth reporting, but it is not this method's
 759        # to report: it is returned as it stands and _handle dead-letters it
 760        # with a reason, which is where every other unhandleable delivery goes.
 761        # An interceptor between here and there sees the same thing the handler
 762        # returned, which is the honest thing to show it.
 763        decision: Ack = await returned if inspect.isawaitable(returned) else returned
 764        return decision
 765
 766    def _decide(self, envelope: Envelope, decision: Ack) -> tuple[Settlement, Wait | None]:
 767        """What is going to happen to this delivery, before anything happens to
 768        it.
 769
 770        Worked out on its own, and without touching the broker, so that it can
 771        be announced first. The gap this closes is a small one to describe and a
 772        wide one to fall into: a handler asking for a retry it has no attempts
 773        left for is dead-lettered, and anything reading the handler's answer
 774        instead of this one records a retry that never happened.
 775
 776        :param envelope: the message's metadata, for the attempt and the age
 777        :param decision: what the handler answered
 778        :returns: the settlement, and the wait when there is another attempt —
 779            which the settlement does not carry, because whether a wait is spent
 780            here or on a rung queue is this consumer's business and not a
 781            listener's
 782        """
 783        if decision.action is Action.ACCEPT:
 784            return Settlement(OUTCOME_ACKED), None
 785
 786        if decision.action is Action.REJECT:
 787            return (
 788                Settlement(
 789                    OUTCOME_REJECTED,
 790                    reason=f"the handler rejected it: {_describe(decision.error)}",
 791                ),
 792                None,
 793            )
 794
 795        if decision.action is Action.PARK:
 796            # The handler read the message and found nothing it could read. The
 797            # engine reaches the same conclusion for a body its codec refuses,
 798            # and both end up in the same queue for the same reason: a message
 799            # nobody can read is a producer problem, and it is only findable if
 800            # it is not filed with the messages that merely ran out of luck.
 801            return (
 802                Settlement(
 803                    OUTCOME_PARKED,
 804                    reason=f"the handler parked it: {_describe(decision.error)}",
 805                ),
 806                None,
 807            )
 808
 809        if decision.action is Action.IN_PROGRESS:
 810            # Somebody else holds the message. Not a failure of this one, so the
 811            # retry policy is not asked: it can neither spend an attempt nor run
 812            # out and dead-letter a message nobody has failed to handle.
 813            delay = decision.delay if decision.delay is not None else ZERO
 814            return Settlement(OUTCOME_IN_PROGRESS, delay=delay), Wait(delay, in_broker=False)
 815
 816        if isinstance(decision.error, _StopReadingError):
 817            return (
 818                Settlement(
 819                    OUTCOME_STOPPED,
 820                    reason=f"the reader stopped at it: {_describe(decision.error)}",
 821                ),
 822                None,
 823            )
 824
 825        if isinstance(decision.error, FatalError):
 826            # The handler asked for a retry but marked the reason as one that
 827            # will not change. Honouring the mark rather than the request is the
 828            # point of having it.
 829            return (
 830                Settlement(
 831                    OUTCOME_DEAD_LETTERED,
 832                    reason=(
 833                        "the handler reported an unprocessable message: "
 834                        f"{_describe(decision.error)}"
 835                    ),
 836                ),
 837                None,
 838            )
 839
 840        wait = self._retry.next_wait(envelope.attempt, envelope.age)
 841        if wait is None:
 842            return (
 843                Settlement(
 844                    OUTCOME_DEAD_LETTERED,
 845                    reason=f"{self._exhausted(envelope)}: {_describe(decision.error)}",
 846                ),
 847                None,
 848            )
 849
 850        return Settlement(OUTCOME_RETRIED, delay=wait.delay), wait
 851
 852    async def _carry_out(
 853        self,
 854        delivery: Delivery,
 855        envelope: Envelope,
 856        settlement: Settlement,
 857        wait: Wait | None,
 858    ) -> None:
 859        """Does what :meth:`_decide` decided, and counts it as decided.
 860
 861        Every counter here is chosen from the :class:`~acemq_amqp.ack.Settlement`
 862        and never from the handler's :class:`~acemq_amqp.ack.Ack`, which is the
 863        same rule the delivery's span follows. A handler asking for a retry it
 864        has no attempts left for is dead-lettered, and a counter that read the
 865        request rather than the answer would report a retry for a message
 866        nothing will ever try again — so the dead letters would be undercounted
 867        by exactly the messages an operator most wants to find.
 868
 869        One ``acemq.consume.total`` per delivery, carrying the outcome, and then
 870        whichever of the standalone counters applies. ``retried`` and
 871        ``dead_lettered`` are both an outcome here and a counter of their own,
 872        which is what Java does and is not a redundancy: the outcome says what
 873        was decided about a delivery, and the counter says how many messages are
 874        going round again or have been set aside, which is the number an alert
 875        is written against.
 876        """
 877        self._observer.count(
 878            METRIC_CONSUME_TOTAL, 1, {**self._labels, TAG_OUTCOME: settlement.outcome}
 879        )
 880
 881        if settlement.outcome == OUTCOME_ACKED:
 882            await delivery.ack()
 883            return
 884
 885        if settlement.outcome == OUTCOME_STOPPED:
 886            # Returned, not acknowledged: on a stream neither moves the log, and
 887            # a requeue is the honest word for a message nothing has dealt with.
 888            log.error(
 889                "acemq: stopped reading %s at %s: %s",
 890                self._queue,
 891                envelope.id,
 892                settlement.reason,
 893            )
 894            self._halt()
 895            await delivery.nack(True)
 896            return
 897
 898        if settlement.outcome == OUTCOME_PARKED:
 899            # ``_park`` counts it, exactly as it does for a body that would not
 900            # decode. There is one parked counter and one parked queue whether
 901            # the codec or the handler was the one that could not read it.
 902            await self._park(delivery, envelope, settlement.reason or "")
 903            return
 904
 905        if wait is None:
 906            await self._dead_letter(delivery, envelope, settlement.reason or "")
 907            return
 908
 909        if settlement.outcome == OUTCOME_IN_PROGRESS:
 910            await self._put_back(delivery, envelope, wait.delay)
 911            return
 912
 913        if wait.in_broker and await self._retry_in_broker(delivery, envelope, wait.delay):
 914            return
 915
 916        if wait.delay > ZERO:
 917            # Waiting here holds the delivery, and so holds one of this
 918            # consumer's prefetch slots. For a wait of a few seconds that is the
 919            # cheaper of the two costs; for a longer one it is not, which is why
 920            # the policy has a threshold and the long waits went to a rung queue
 921            # a few lines above.
 922            await asyncio.sleep(wait.delay.total_seconds())
 923
 924        await self._retry_again(delivery, envelope, wait.delay)
 925
 926    def _exhausted(self, envelope: Envelope) -> str:
 927        """Why there is no next attempt, in words an operator can act on."""
 928        if envelope.attempt >= self._retry.max_attempts:
 929            attempts = self._retry.max_attempts
 930            return f"exhausted {attempts} attempt{'' if attempts == 1 else 's'}"
 931        return f"exceeded the maximum message age of {self._retry.max_message_age}"
 932
 933    async def _retry_in_broker(
 934        self, delivery: Delivery, envelope: Envelope, delay: timedelta
 935    ) -> bool:
 936        """Parks the message on ``{queue}.retry.{delay}`` and lets the broker
 937        return it.
 938
 939        The rung's ``x-message-ttl`` is the delay and its dead-letter target is
 940        this queue, so the wait costs nothing here: no delivery held, no prefetch
 941        slot spent, and — the reason it exists — nothing lost when this process
 942        restarts halfway through. A consumer sleeping on a five-minute backoff
 943        that dies at minute one does not resume at minute one; the broker
 944        redelivers the unacknowledged message immediately, and the policy that
 945        said five minutes delivers in none.
 946
 947        The obvious simplification is one rung queue and a per-message
 948        ``expiration`` instead of several with fixed TTLs. It does not work.
 949        RabbitMQ only ever expires the message at the *head* of a queue, so a
 950        message with a ten-minute TTL at the front holds back every thirty-second
 951        one behind it, and the delays that come out bear no resemblance to the
 952        ones that went in. Never set a per-message TTL for this.
 953
 954        The attempt advances here exactly as it does on an immediate retry: the
 955        counter belongs to the message, and a message that has been round the
 956        broker is no less on its second attempt than one that waited here.
 957
 958        :returns: whether the rung took it. ``False`` means no such queue, and
 959            the caller should fall back to waiting here
 960        """
 961        rung = naming.retry_queue(self._queue, delay)
 962        next_attempt = envelope.with_(attempt=envelope.attempt + 1)
 963        try:
 964            routed = await self._republish(delivery, rung, next_attempt)
 965        except _HopRefusedError:
 966            # The rung is there and would not take it. Requeued at once, with
 967            # nothing else on this consumer settled, rather than waited out
 968            # here: the broker is the one saying no, and holding the delivery
 969            # for the whole delay would stall this consumer for nothing.
 970            self._observer.count(METRIC_RETRIED_TOTAL, 1, {**self._labels, "where": "requeued"})
 971            await delivery.nack(True)
 972            return True
 973        if not routed:
 974            # Kept even though a consumer declares its own rungs when it starts,
 975            # because the rung can still be missing: a consumer started with
 976            # ``declare=False`` declares nothing, and a rung deleted under a
 977            # running consumer is gone whoever declared it. What has changed is
 978            # what it means — it used to be an ordinary topology mistake and is
 979            # now either a deliberate opt-out or somebody removing queues.
 980            #
 981            # Degraded rather than fatal: the message is still deliverable, and
 982            # waiting for it here is what this library did before there were
 983            # rungs. Counted as well as logged, because this is the one failure
 984            # here that nothing else shows: the message is still retried and the
 985            # wait still happens, so a dashboard reads as normal while the reason
 986            # the rung exists is quietly gone.
 987            self._observer.count(METRIC_RUNG_MISSING, 1, {**self._labels, "rung": rung})
 988            log.error(
 989                "acemq: %s is not on the broker, so %s will wait %s in this consumer "
 990                "instead; declare it with Topology().queue(%r, retry=policy), or let "
 991                "the consumer declare it by leaving declare=True",
 992                rung,
 993                envelope.id,
 994                delay,
 995                self._queue,
 996            )
 997            return False
 998
 999        self._observer.count(METRIC_RETRIED_TOTAL, 1, {**self._labels, "where": "broker"})
1000        log.info(
1001            "acemq: retrying %s from %s, attempt %d of %d, after %s in %s",
1002            envelope.id,
1003            self._queue,
1004            next_attempt.attempt,
1005            self._retry.max_attempts,
1006            delay,
1007            rung,
1008        )
1009        await delivery.ack()
1010        return True
1011
1012    async def _retry_again(
1013        self, delivery: Delivery, envelope: Envelope, delay: timedelta
1014    ) -> None:
1015        """Puts the message back on its own queue, one attempt further on.
1016
1017        Republished rather than requeued, because a requeue returns the bytes
1018        the broker was given: the attempt header would still read what the
1019        publisher wrote however many times the message had come round, and the
1020        count would live only in this process's memory, which is the one place
1021        it is lost when the process that has been failing restarts.
1022
1023        The cost is that the message goes to the back of the queue rather than
1024        the front, so a retry is no longer in order with its neighbours. For a
1025        message that has already failed once, that is the better trade.
1026        """
1027        next_attempt = envelope.with_(attempt=envelope.attempt + 1)
1028        try:
1029            delivered = await self._republish(delivery, self._queue, next_attempt)
1030        except _HopRefusedError:
1031            delivered = False
1032        if not delivered:
1033            # The queue we are consuming has gone. Requeued rather than
1034            # acknowledged, because dropping it here would lose a message over a
1035            # broker change nobody told this consumer about.
1036            #
1037            # Counted as a retry all the same, and it is one: the settlement
1038            # said ``retried``, the span says ``retried``, and the broker is
1039            # about to hand the message back. Leaving it uncounted was the one
1040            # place where the counters and the span disagreed about the same
1041            # delivery. The label says which path it took, because a requeue
1042            # keeps the attempt header it arrived with and the other two do not.
1043            self._observer.count(METRIC_RETRIED_TOTAL, 1, {**self._labels, "where": "requeued"})
1044            log.error(
1045                "acemq: cannot republish %s onto %s for attempt %d; returning it to the broker",
1046                envelope.id,
1047                self._queue,
1048                next_attempt.attempt,
1049            )
1050            await delivery.nack(True)
1051            return
1052
1053        self._observer.count(METRIC_RETRIED_TOTAL, 1, {**self._labels, "where": "consumer"})
1054        log.info(
1055            "acemq: retrying %s from %s, attempt %d of %d, after %s",
1056            envelope.id,
1057            self._queue,
1058            next_attempt.attempt,
1059            self._retry.max_attempts,
1060            delay,
1061        )
1062        await delivery.ack()
1063
1064    async def _put_back(
1065        self, delivery: Delivery, envelope: Envelope, delay: timedelta
1066    ) -> None:
1067        """Returns a message somebody else is working on, attempt unchanged.
1068
1069        :meth:`_retry_again` without the increment: the attempt counts this
1070        message's failures, and a claim held elsewhere is not one of them.
1071        """
1072        if delay > ZERO:
1073            await asyncio.sleep(delay.total_seconds())
1074        try:
1075            delivered = await self._republish(delivery, self._queue, envelope)
1076        except _HopRefusedError:
1077            delivered = False
1078        if delivered:
1079            await delivery.ack()
1080            return
1081        log.error(
1082            "acemq: cannot put %s back onto %s; returning it to the broker",
1083            envelope.id,
1084            self._queue,
1085        )
1086        await delivery.nack(True)
1087
1088    async def _park(self, delivery: Delivery, envelope: Envelope, reason: str) -> None:
1089        """Sends the message to ``{queue}.parked`` with the reason attached.
1090
1091        Where a message goes when it never reached the handler at all. Somebody
1092        has to look at it, and what they need to know first is that it was
1093        unreadable rather than unlucky.
1094        """
1095        # The same counter a dead-lettering moves, separated by the outcome
1096        # rather than by a metric of its own — which is what Java settled on, and
1097        # what makes "how much is this queue giving up on" one number that can
1098        # then be split into the two problems it is made of.
1099        self._observer.count(
1100            METRIC_DEAD_LETTERED_TOTAL, 1, {**self._labels, TAG_OUTCOME: OUTCOME_PARKED}
1101        )
1102        await self._set_aside(delivery, envelope, naming.parked_queue(self._queue), reason)
1103
1104    async def _dead_letter(self, delivery: Delivery, envelope: Envelope, reason: str) -> None:
1105        """Sends the message to ``{queue}.dlq`` with the reason attached, and
1106        acknowledges the original.
1107
1108        Acknowledging a message that failed looks wrong and is what makes this
1109        reliable: the message has already been safely republished somewhere
1110        else, so acknowledging the original is removing the copy that has been
1111        dealt with. Rejecting it instead would either requeue it into a hot loop
1112        or, with a dead-letter exchange configured on the queue, send it
1113        somewhere this consumer did not choose and without the reason.
1114
1115        The reason travels as an envelope field, so a consumer of the
1116        dead-letter queue reads it back through the API rather than having to
1117        know the wire header name.
1118        """
1119        self._observer.count(
1120            METRIC_DEAD_LETTERED_TOTAL,
1121            1,
1122            {**self._labels, TAG_OUTCOME: OUTCOME_DEAD_LETTERED},
1123        )
1124        await self._set_aside(
1125            delivery, envelope, naming.dead_letter_queue(self._queue), reason
1126        )
1127
1128    async def _set_aside(
1129        self, delivery: Delivery, envelope: Envelope, target: str, reason: str
1130    ) -> None:
1131        """Republishes to ``target`` with the reason, then acknowledges."""
1132        failed = envelope.with_(error=reason)
1133        try:
1134            delivered = await self._republish(delivery, target, failed)
1135        except _HopRefusedError:
1136            delivered = False
1137        if not delivered:
1138            # Requeued, never rejected (AceMQ TCK requirements AMQP-PUB-002 and
1139            # AMQP-RETRY-007). Rejecting without requeue dropped the message, or
1140            # dead-lettered it through the source queue's own dead-letter
1141            # exchange somewhere it does not belong, the moment the broker
1142            # refused the copy. Requeued, it comes back and is set aside again
1143            # once the broker takes it.
1144            self._observer.count(
1145                METRIC_SET_ASIDE_FAILED, 1, {**self._labels, TAG_TARGET: target}
1146            )
1147            log.error(
1148                "acemq: cannot move %s to %s (%s); returning it to the broker",
1149                envelope.id,
1150                target,
1151                reason,
1152            )
1153            await asyncio.sleep(SET_ASIDE_REFUSED_DELAY)
1154            await delivery.nack(True)
1155            return
1156
1157        log.warning(
1158            "acemq: set aside %s from %s after %d attempts, into %s: %s",
1159            envelope.id,
1160            self._queue,
1161            envelope.attempt,
1162            target,
1163            reason,
1164        )
1165        await delivery.ack()
1166
1167    async def _republish(self, delivery: Delivery, queue: str, envelope: Envelope) -> bool:
1168        """Sends the original bytes to a queue by name, and says whether they
1169        arrived.
1170
1171        Through the default exchange, which routes to the queue whose name
1172        matches the routing key, and mandatory so that a queue that is not there
1173        is an answer rather than a silence. The body goes back exactly as it
1174        came: re-encoding through a class that has since changed would replace
1175        what was committed with something else.
1176        """
1177        try:
1178            result = await self._connection.publish_raw(
1179                "",
1180                queue,
1181                Outbound(
1182                    body=delivery.body,
1183                    content_type=delivery.content_type or "",
1184                    message_id=envelope.id,
1185                    headers=envelope.to_headers(routing_key=delivery.routing_key),
1186                    persistent=True,
1187                    mandatory=True,
1188                ),
1189            )
1190        except PublishError as refused:
1191            # The broker nacked it, or would not take it while blocked. Raised
1192            # as the caller's to settle, because what to do differs: a refused
1193            # rung means requeue now, where a missing rung means wait here.
1194            # Escaping further left the delivery unsettled for the life of the
1195            # channel, which is what Ruby did before 0.7.12.
1196            log.error("acemq: the broker refused %s onto %s: %s", envelope.id, queue, refused)
1197            raise _HopRefusedError(str(refused)) from refused
1198        return result.routed
1199
1200    def _halt(self) -> None:
1201        """Stops this consumer from inside one of its own handlers.
1202
1203        The close runs as a task of its own, because it waits for the workers
1204        and the caller is one of them.
1205        """
1206        self._halted = True
1207        if self._halting is None:
1208            self._halting = asyncio.get_running_loop().create_task(self.close())
1209
1210    async def close(self, *, timeout: float | None = DEFAULT_DRAIN_TIMEOUT) -> bool:
1211        """Stops the consumer and waits, for up to ``timeout``, for the handlers
1212        already running.
1213
1214        A message being worked on when this is called is finished and settled,
1215        rather than abandoned for the broker to hand to somebody else. A message
1216        that had been delivered but not started is given back instead: it is the
1217        broker's to hand to another consumer, and holding it here only to work
1218        through a retry delay would make closing take as long as the schedule.
1219
1220        A handler still running when the time is up is cancelled, and its message
1221        is left unsettled — neither acknowledged nor rejected — so the broker
1222        hands it out again once the channel goes. Shutdown is never the reason a
1223        message is lost or dead-lettered. The same happens when the caller
1224        cancels closing, ``asyncio.wait_for`` included, and that cancellation is
1225        raised again once the consumer has been cleaned up.
1226
1227        The subscription is released last, after everything has been settled,
1228        because a settlement travels on the channel its delivery arrived on.
1229
1230        :param timeout: seconds to wait for every running handler together;
1231            ``None`` waits for as long as they take
1232        :returns: ``True`` if every handler finished, ``False`` if the time ran
1233            out first and some were cut off — the consumer is stopped either way
1234        """
1235        if self._closed:
1236            halting = self._halting
1237            if halting is not None and halting is not asyncio.current_task():
1238                # Stopped by its own handler and still closing: closing the
1239                # connection underneath that would cut it off halfway.
1240                return await halting
1241            return True
1242        self._closed = True
1243
1244        running: set[asyncio.Task[None]] = set()
1245        try:
1246            if self._subscription is not None:
1247                await self._subscription.stop()
1248
1249            while True:
1250                try:
1251                    pending = self._work.get_nowait()
1252                except asyncio.QueueEmpty:
1253                    break
1254                if pending is not None:
1255                    await pending.nack(True)
1256
1257            for _ in self._workers:
1258                self._work.put_nowait(None)
1259            if self._workers:
1260                _, running = await asyncio.wait(self._workers, timeout=timeout)
1261        finally:
1262            # Reached with workers still running for two reasons: the deadline
1263            # passed, or the caller cancelled us. Either way they are cancelled
1264            # before the channel goes, so nothing settles a message on a channel
1265            # that is closing — and a cancellation that came from the caller is
1266            # not caught here, so it carries on out once this has run.
1267            stragglers = [worker for worker in self._workers if not worker.done()]
1268            for worker in stragglers:
1269                worker.cancel()
1270            if stragglers:
1271                await asyncio.wait(stragglers)
1272            if self._subscription is not None:
1273                await self._subscription.close()
1274            self._connection._untrack(self)
1275
1276        for worker in self._workers:
1277            # A worker that was already cancelled — a task group unwinding, a
1278            # shutdown that cancelled the loop's tasks before closing the
1279            # connection — is not news to report to a caller who is merely
1280            # closing. One that died of its own accord is.
1281            failure = None if worker.cancelled() else worker.exception()
1282            if failure is not None:
1283                raise failure
1284        return not running
1285
1286    async def __aenter__(self) -> Consumer:
1287        return self
1288
1289    async def __aexit__(self, *_: object) -> None:
1290        # Not returned: a true value from here tells the interpreter that the
1291        # exception leaving the block was handled.
1292        await self.close()
1293
1294
1295class Connection:
1296    """A connection to a broker, and the defaults everything on it inherits.
1297
1298    Built by :func:`connect` in the ordinary case. Taking a transport directly
1299    is for a fake in a test, or for a connection made with settings a URL cannot
1300    carry.
1301
1302    :param transport: how to reach the broker
1303    :param codec: what publishers and consumers use unless they say otherwise
1304    :param origin: what to stamp on published messages, conventionally
1305        ``service@host``
1306    :param retry: what consumers use unless they say otherwise. The default is
1307        one delivery and no second chance, so a handler that calls
1308        ``retry()`` on a connection with no policy dead-letters the message and
1309        says so in the reason. That is deliberate: the alternative default is an
1310        immediate requeue, which is a hot loop against a broker that nobody
1311        asked for
1312    :param prefetch: how many unacknowledged messages a consumer holds
1313    :param max_outstanding_publishes: how many publishes may be waiting for the
1314        broker at once. The ceiling that turns a memory leak into backpressure:
1315        without one, a caller publishing faster than the broker answers
1316        accumulates unconfirmed messages until the process dies, which looks
1317        like throughput right up to the moment it does not. A thousand by
1318        default, which is what Java's ``maxOutstandingPublishes`` and .NET's
1319        ``MaxOutstandingPublishes`` default to
1320    :param confirm_timeout: how long a publish waits for one of those permits,
1321        and then for the broker's confirm, before giving up. Ten seconds by
1322        default, the same as Java's ``confirmTimeout``. Reaching it raises
1323        rather than waiting on, because a publisher stalled for ever behind a
1324        broker that has stopped answering is the failure this bound exists to make visible
1325    :param on_publish: cross-cutting behaviour to wrap every publish on this
1326        connection in, outermost first. See :mod:`acemq_amqp.interceptors`
1327    :param on_consume: the same around every handler.
1328        :meth:`intercept_publish` and :meth:`intercept_consume` add more later
1329    :param observer: where the numbers go. Nothing by default, so a service
1330        that wants none pays for none. See :mod:`acemq_amqp.telemetry`
1331    """
1332
1333    def __init__(
1334        self,
1335        transport: Transport,
1336        *,
1337        codec: Codec | None = None,
1338        origin: str | None = None,
1339        retry: RetryPolicy | None = None,
1340        prefetch: int = DEFAULT_PREFETCH,
1341        max_outstanding_publishes: int = DEFAULT_MAX_OUTSTANDING_PUBLISHES,
1342        confirm_timeout: timedelta = DEFAULT_CONFIRM_TIMEOUT,
1343        on_publish: Sequence[PublishInterceptor] = (),
1344        on_consume: Sequence[ConsumeInterceptor] = (),
1345        observer: Observer | None = None,
1346    ) -> None:
1347        if prefetch < 0:
1348            raise ValueError(f"acemq: prefetch must not be negative, got {prefetch}")
1349        if max_outstanding_publishes < 1:
1350            raise ValueError(
1351                "acemq: max_outstanding_publishes must be at least 1, got "
1352                f"{max_outstanding_publishes}"
1353            )
1354        if confirm_timeout <= timedelta(0):
1355            raise ValueError(
1356                f"acemq: confirm_timeout must be positive, got {confirm_timeout}"
1357            )
1358        self._transport = transport
1359        self._observer: Observer = observer or NullObserver()
1360        self._codec = codec or JsonCodec()
1361        self._origin = origin or default_origin()
1362        self._retry = retry or no_retry()
1363        self._prefetch = prefetch
1364        self._max_outstanding = max_outstanding_publishes
1365        self._confirm_timeout = confirm_timeout
1366        # Built here rather than on first use. An asyncio.Semaphore has bound no
1367        # loop at construction since 3.10, so it is safe to make one outside a
1368        # running loop, and making it here means every publish on this connection
1369        # shares the one counter however many tasks are publishing.
1370        self._outstanding = asyncio.Semaphore(max_outstanding_publishes)
1371        self._in_flight_publishes = 0
1372        self._consumers: list[Consumer] = []
1373        self._publishing: list[PublishInterceptor] = list(on_publish)
1374        self._consuming: list[ConsumeInterceptor] = list(on_consume)
1375        self._closed = False
1376
1377    @property
1378    def transport(self) -> Transport:
1379        """The transport underneath, for anything this library does not wrap."""
1380        return self._transport
1381
1382    @property
1383    def codec(self) -> Codec:
1384        """The codec publishers and consumers use unless told otherwise."""
1385        return self._codec
1386
1387    @property
1388    def origin(self) -> str:
1389        """What published messages are stamped with."""
1390        return self._origin
1391
1392    @property
1393    def retry(self) -> RetryPolicy:
1394        """The retry policy consumers use unless told otherwise."""
1395        return self._retry
1396
1397    @property
1398    def observer(self) -> Observer:
1399        """Where this connection's numbers go."""
1400        return self._observer
1401
1402    @property
1403    def max_outstanding_publishes(self) -> int:
1404        """How many publishes may be waiting for the broker at once."""
1405        return self._max_outstanding
1406
1407    @property
1408    def confirm_timeout(self) -> timedelta:
1409        """How long a publish waits for room before giving up."""
1410        return self._confirm_timeout
1411
1412    @property
1413    def outstanding_publishes(self) -> int:
1414        """How many publishes are waiting for the broker right now.
1415
1416        What a stalled publisher looks like from outside: a number pinned at
1417        :attr:`max_outstanding_publishes` is a broker that has stopped answering,
1418        and it says so before the first :class:`~acemq_amqp.PublishError` does.
1419        """
1420        # Counted here rather than read off the semaphore, which keeps its count
1421        # private. Raised after the permit is taken and lowered before it is
1422        # given back, both inside publish_raw, so it never reads high.
1423        return self._in_flight_publishes
1424
1425    @property
1426    def consumers(self) -> tuple[Consumer, ...]:
1427        """The consumers running on this connection.
1428
1429        A snapshot, and public because a health check that has to say whether
1430        the consumers are alive should not need private access to find them —
1431        the same rule an interceptor follows.
1432        """
1433        return tuple(self._consumers)
1434
1435    @property
1436    def closed(self) -> bool:
1437        """Whether this connection has been closed."""
1438        return self._closed
1439
1440    @property
1441    def blocked(self) -> bool | None:
1442        """Whether the broker has blocked this connection, or ``None`` when the
1443        transport cannot be asked.
1444
1445        RabbitMQ blocks a connection when it is low on memory or disk, and while
1446        it lasts it stops reading that connection's socket: everything sent —
1447        a publish, a declaration, :meth:`health`'s own probe — waits rather than
1448        failing. It is the broker protecting itself and it is not an error, so
1449        it is worth telling apart from the broker having gone away, which looks
1450        identical from outside and wants the opposite response.
1451
1452        ``None`` means the question could not be asked at all, which is a
1453        different fact from ``False`` and is reported as one: a transport that
1454        does not implement
1455        :class:`~acemq_amqp.transport.BlockedState`, or one whose client has
1456        moved the state out of reach. See :attr:`blocked_reason` for why there
1457        may be a boolean and no reason to go with it.
1458        """
1459        transport = self._transport
1460        return transport.blocked if isinstance(transport, BlockedState) else None
1461
1462    @property
1463    def blocked_reason(self) -> str | None:
1464        """What the broker said when it blocked this connection, if anything.
1465
1466        ``None`` when the connection is not blocked, and also ``None`` when the
1467        transport is blocked but cannot say why — which is what the RabbitMQ
1468        transport answers, because aio-pika reads RabbitMQ's reason and does not
1469        keep it. Reporting the block without the reason is the honest half;
1470        inventing a reason would read exactly like one the broker sent.
1471        """
1472        transport = self._transport
1473        return transport.blocked_reason if isinstance(transport, BlockedState) else None
1474
1475    async def health(self, timeout: float = DEFAULT_HEALTH_TIMEOUT) -> HealthReport:
1476        """Whether this connection can reach its broker, and its consumers run.
1477
1478        The broker half is a declaration of a temporary queue, which is the
1479        cheapest thing AMQP offers that actually proves the connection works. A
1480        TCP connection that is open but wedged — the broker paused, the network
1481        black-holing — answers a socket-level check exactly as a healthy one
1482        does, right up until something is asked of it.
1483
1484        The consumer half is the one a probe usually wants and nothing outside
1485        can see. A consumer whose workers have died without it being closed is
1486        one the broker is still sending messages to and nothing is reading, and
1487        from outside that is indistinguishable from a quiet queue.
1488
1489        **A blocked connection is up, with the reason.** The broker blocks a
1490        connection when it is low on disk or memory, and an application that
1491        fails its own readiness check for it is one an orchestrator restarts
1492        into the same blocked broker, having thrown away whatever it was
1493        holding. ``parts["blocked"]`` carries the state either way, and is
1494        ``None`` when the transport could not be asked — see :attr:`blocked`.
1495
1496        **The probe is bounded.** A blocked broker stops reading the socket, so
1497        the round trip this makes is precisely the thing that does not come back
1498        when something is wrong; without a deadline of its own a health check
1499        hangs, and a readiness endpoint that hangs takes the instance out of
1500        rotation with no report at all. A probe that runs out of time is
1501        abandoned rather than waited for, because a request that cannot be
1502        answered cannot reliably be cancelled either.
1503
1504        It costs a round trip, so it is not something to call per request. Wire
1505        it to a readiness probe and let the probe's interval decide how often.
1506
1507        :param timeout: how long to give the broker's answer, three seconds by
1508            default. Shorter than the deadline
1509            :func:`~acemq_amqp.telemetry.aggregate_health` puts around a whole
1510            set of checks, so that this report rather than that one is what an
1511            operator reads when a broker stops answering
1512        :returns: the report. Degraded means working but worth an alert
1513        """
1514        checked = datetime.now(timezone.utc)
1515        consumers = self.consumers
1516        stalled = [consumer.queue for consumer in consumers if not consumer.running]
1517        blocked = self.blocked
1518        parts: dict[str, Any] = {
1519            "consumers": len(consumers),
1520            "in-flight": sum(consumer.in_flight for consumer in consumers),
1521            "blocked": blocked,
1522        }
1523        reason = self.blocked_reason
1524        if reason:
1525            parts["blocked-reason"] = reason
1526
1527        if self._closed:
1528            return HealthReport(
1529                HealthStatus.DOWN, "the connection has been closed", checked, parts
1530            )
1531
1532        if blocked:
1533            # Asked before the probe rather than after it, because the probe is
1534            # what a blocked broker will not answer: a round trip started here
1535            # would spend the whole deadline arriving at the answer this already
1536            # has.
1537            return self._blocked_report(checked, parts, stalled, reason)
1538
1539        # Asking whether a queue nothing has ever declared exists, rather than
1540        # declaring a temporary one. It is the same round trip and it proves the
1541        # same thing, and it creates nothing at all: an exclusive queue is only
1542        # released when the channel that declared it closes, so a probe that
1543        # declared one would leave a queue on the broker for the life of the
1544        # connection and a new one behind every restart.
1545        probe = f"acemq-health-{uuid.uuid4().hex}"
1546        started = time.monotonic()
1547        try:
1548            await self._probe_within(probe, timeout)
1549        except asyncio.TimeoutError:
1550            # A round trip that does not come back is the ordinary way a block
1551            # shows itself, and the notification may have arrived while this was
1552            # waiting. Asked again rather than assumed, because "the broker is
1553            # protecting itself" and "the broker has gone" are the same silence.
1554            blocked = self.blocked
1555            parts["blocked"] = blocked
1556            reason = self.blocked_reason
1557            if reason:
1558                parts["blocked-reason"] = reason
1559            if blocked:
1560                return self._blocked_report(checked, parts, stalled, reason)
1561            return HealthReport(
1562                HealthStatus.DOWN,
1563                f"the broker did not answer within {timeout:g}s",
1564                checked,
1565                parts,
1566            )
1567        except Exception as failure:
1568            parts["error"] = _describe(failure)
1569            return HealthReport(
1570                HealthStatus.DOWN, f"the broker did not answer: {failure}", checked, parts
1571            )
1572        parts["round-trip"] = round(time.monotonic() - started, 4)
1573
1574        if stalled:
1575            # Degraded rather than down: the connection works, and a replacement
1576            # instance would almost certainly stall the same way. Worth waking
1577            # somebody; not worth taking this one out of rotation.
1578            return HealthReport(
1579                HealthStatus.DEGRADED,
1580                _stalled_detail(stalled),
1581                checked,
1582                {**parts, "stalled": sorted(stalled)},
1583            )
1584        return HealthReport(HealthStatus.UP, "", checked, parts)
1585
1586    def _blocked_report(
1587        self,
1588        checked: datetime,
1589        parts: dict[str, Any],
1590        stalled: list[str],
1591        reason: str | None,
1592    ) -> HealthReport:
1593        """What a blocked connection reports: up, with the reason.
1594
1595        Up for the block itself, and still degraded when a consumer of this
1596        process has stopped reading — that is this instance's own failure rather
1597        than the broker's, it outlives the alarm, and a block is not a reason to
1598        stop saying so.
1599        """
1600        detail = self._blocked_detail(reason)
1601        if stalled:
1602            return HealthReport(
1603                HealthStatus.DEGRADED,
1604                f"{_stalled_detail(stalled)}; and {detail}",
1605                checked,
1606                {**parts, "stalled": sorted(stalled)},
1607            )
1608        return HealthReport(HealthStatus.UP, detail, checked, parts)
1609
1610    @staticmethod
1611    def _blocked_detail(reason: str | None) -> str:
1612        """The blocked sentence, with the broker's reason when there is one.
1613
1614        The reason follows a colon, which is how Go and Ruby write it too —
1615        ``blockedPrefix + ": " + reason`` and ``"#{BLOCKED}: #{reason}"``. One
1616        shape across the family means one alert rule reads a blocked broker
1617        whatever language the service happens to be written in.
1618        """
1619        return BLOCKED_DETAIL if not reason else f"{BLOCKED_DETAIL}: {reason}"
1620
1621    async def _probe_within(self, name: str, timeout: float) -> None:
1622        """One round trip to the broker, given ``timeout`` to come back.
1623
1624        The probe runs as a task that is abandoned rather than awaited when the
1625        deadline passes, which is the difference between a bounded check and one
1626        that merely looks bounded: cancelling a request to a broker that has
1627        stopped reading its socket means waiting for a cancellation that travels
1628        the same way the request did.
1629
1630        :raises asyncio.TimeoutError: when the broker did not answer in time
1631        """
1632        probe = asyncio.ensure_future(self._probe(name))
1633        try:
1634            done, _ = await asyncio.wait({probe}, timeout=timeout)
1635        except asyncio.CancelledError:
1636            # The caller gave up on the whole check. Waiting on a task is not
1637            # cancelling it, so it is cancelled here rather than left running
1638            # against a broker nobody is listening to any more.
1639            probe.cancel()
1640            probe.add_done_callback(_retrieved)
1641            raise
1642        if not done:
1643            probe.cancel()
1644            # Whatever it ends as is nobody's news now, and an abandoned task
1645            # whose exception is never retrieved is a warning at collection time
1646            # about a failure that has already been reported as a timeout.
1647            probe.add_done_callback(_retrieved)
1648            raise asyncio.TimeoutError
1649        # Raises what the probe raised, which is what the caller reports.
1650        probe.result()
1651
1652    async def _probe(self, name: str) -> None:
1653        """One round trip to the broker that leaves nothing behind.
1654
1655        A transport that cannot be asked whether a queue exists gets the next
1656        cheapest thing: a temporary queue, removed again straight away. Both
1657        prove the same thing, which is that the connection answers rather than
1658        merely being open.
1659
1660        The temporary queue is classic, and has to be. It is exclusive and
1661        auto-deleting so that it goes when the channel does, and RabbitMQ
1662        refuses a quorum queue that is either — a health check that could not be
1663        declared would report a healthy broker as down.
1664        """
1665        if isinstance(self._transport, QueueAdmin):
1666            await self._transport.queue_exists(name)
1667            return
1668        await self._transport.declare_queue(
1669            name, QueueSpec(durable=False, auto_delete=True, exclusive=True)
1670        )
1671
1672    @property
1673    def publish_interceptors(self) -> tuple[PublishInterceptor, ...]:
1674        """What wraps every publish, outermost first.
1675
1676        A snapshot rather than the list itself, so a publish in progress cannot
1677        be handed a chain that is being edited underneath it.
1678        """
1679        return tuple(self._publishing)
1680
1681    @property
1682    def consume_interceptors(self) -> tuple[ConsumeInterceptor, ...]:
1683        """What wraps every handler, outermost first."""
1684        return tuple(self._consuming)
1685
1686    def intercept_publish(self, interceptor: PublishInterceptor) -> Connection:
1687        """Wraps every publish on this connection in ``interceptor``.
1688
1689        Registered ones run in the order they were added, so this one is
1690        innermost until the next is added. Read at publish time rather than
1691        copied into each publisher, so an interceptor registered during start-up
1692        applies to publishers that already exist — which is what makes it usable
1693        from a framework's wiring rather than only from the line that connects.
1694
1695        Adding at start-up is still what to do. A message already in flight will
1696        not see it, and an interceptor whose whole job is to stamp every message
1697        is not doing it if the first few went without.
1698
1699        :param interceptor: what to wrap the publish in. See
1700            :mod:`acemq_amqp.interceptors`
1701        :returns: this connection, so registrations read as one expression
1702        """
1703        self._publishing.append(interceptor)
1704        return self
1705
1706    def intercept_consume(self, interceptor: ConsumeInterceptor) -> Connection:
1707        """Wraps every handler on this connection in ``interceptor``.
1708
1709        :param interceptor: what to wrap the handler in
1710        :returns: this connection
1711        """
1712        self._consuming.append(interceptor)
1713        return self
1714
1715    async def declare(self, topology: Topology) -> None:
1716        """Applies a topology to this connection's broker.
1717
1718        :param topology: what the broker should have
1719        """
1720        await topology.apply(self._transport)
1721
1722    def publisher(
1723        self,
1724        exchange: str = "",
1725        routing_key: str = "",
1726        *,
1727        codec: Codec | None = None,
1728        persistent: bool = True,
1729        mandatory: bool = True,
1730    ) -> Publisher:
1731        """Builds a publisher for an exchange and routing key.
1732
1733        Publish straight to a queue by leaving the exchange empty: the default
1734        exchange routes to the queue whose name matches the routing key.
1735
1736        :param exchange: where to publish, empty for the default exchange
1737        :param routing_key: what to publish under, or a queue name
1738        :param codec: a codec other than this connection's
1739        :param persistent: ask the broker to write these messages to disk
1740        :param mandatory: fail when a message reaches no queue at all, rather
1741            than letting the broker drop it silently. On by default (AceMQ TCK
1742            requirement AMQP-PUB-006), so a message published to a routing key
1743            nothing is bound to raises :class:`~acemq_amqp.PublishError` with
1744            ``unroutable`` set instead of disappearing. ``mandatory=False`` is the
1745            opt-out, for a fan-out where no subscriber at all is a normal state
1746        :returns: the publisher
1747        """
1748        return Publisher(
1749            self,
1750            exchange,
1751            routing_key,
1752            codec=codec,
1753            persistent=persistent,
1754            mandatory=mandatory,
1755        )
1756
1757    async def consume(
1758        self,
1759        queue: str,
1760        handler: Handler,
1761        *,
1762        codec: Codec | None = None,
1763        retry: RetryPolicy | None = None,
1764        prefetch: int | None = None,
1765        concurrency: int = 1,
1766        tag: str = "",
1767        args: Mapping[str, Any] | None = None,
1768        declare: bool = True,
1769    ) -> Consumer:
1770        """Reads messages from a queue until the returned consumer is closed.
1771
1772        Before it subscribes it declares the queues it will need when a message
1773        fails: ``{queue}.dlq``, ``{queue}.parked``, ``acemq.dlx`` and, when the
1774        retry policy has waits the broker holds, ``acemq.retry`` and the rungs.
1775        See :func:`acemq_amqp.topology.declare_where_failures_go` for exactly
1776        what and why. The source queue is not among them, and neither is
1777        anything a producer needs, so this is not a replacement for declaring a
1778        topology — it is the floor underneath a service that was deployed
1779        without one.
1780
1781        :param queue: what to read
1782        :param handler: what to do with a message; returning an
1783            :class:`~acemq_amqp.Ack` is the decision
1784        :param codec: a codec other than this connection's
1785        :param retry: a policy other than this connection's
1786        :param prefetch: how many unacknowledged messages to hold
1787        :param concurrency: how many messages to work on at once. One by
1788            default, which keeps a queue's messages in order; raising it trades
1789            that order for throughput, which is the right trade for handlers
1790            that spend their time waiting on something else
1791        :param tag: what to call this consumer to the broker
1792        :param args: broker-specific consumer arguments
1793        :param declare: declare the queues above before subscribing. On by
1794            default, because the alternative default loses messages silently.
1795            Turn it off for a login with no ``configure`` permission on the
1796            vhost, which is refused by the broker rather than ignored, and for a
1797            tool draining a queue it does not own — a one-off reader of
1798            ``orders.dlq`` has no business creating ``orders.dlq.dlq``. A
1799            consumer started this way still publishes to those queues, so
1800            somebody else has to have declared them
1801        :returns: the running consumer
1802        """
1803        if self._closed:
1804            raise AceMQError("acemq: this connection is closed")
1805
1806        consumer = Consumer(
1807            self,
1808            queue,
1809            handler,
1810            codec=codec or self._codec,
1811            retry=retry or self._retry,
1812            concurrency=concurrency,
1813            declare=declare,
1814        )
1815        self._consumers.append(consumer)
1816        try:
1817            await consumer._start(
1818                self._prefetch if prefetch is None else prefetch,
1819                tag,
1820                args or {},
1821            )
1822        except BaseException:
1823            self._untrack(consumer)
1824            raise
1825        return consumer
1826
1827    def pipeline(self, name: str) -> PipelineBuilder:
1828        """Starts declaring a pipeline: steps in order, a queue behind each.
1829
1830        The exchange is ``name`` and each step's queue is ``{name}.{step}``, as
1831        in Java, .NET, Go and Ruby. See
1832        :class:`~acemq_amqp.patterns.PipelineBuilder`.
1833
1834        :param name: the pipeline's name, which is also its exchange
1835        :returns: a builder; nothing is declared until its ``build()``
1836        """
1837        from .patterns.routingslip import PipelineBuilder
1838
1839        return PipelineBuilder(self, name)
1840
1841    async def publish_raw(
1842        self, exchange: str, routing_key: str, message: Outbound
1843    ) -> PublishResult:
1844        """Sends bytes that are already encoded, with headers already rendered.
1845
1846        For the retry and dead-letter hops, and for anything else replaying a
1847        message recorded earlier: the payload's class may not exist any more,
1848        and re-encoding it would produce different bytes from the ones that were
1849        committed. Ordinary publishing goes through :class:`Publisher`.
1850
1851        **This is the one place the outstanding-publish bound is taken.** Every
1852        publish in the library comes through here — a :class:`Publisher`, a
1853        retry rung, a dead letter, a replay — so one permit counts them all, and
1854        :meth:`Publisher.send_all` cannot put more messages on the wire at once
1855        than :attr:`max_outstanding_publishes` allows however long the list it
1856        was given is.
1857
1858        :param exchange: where to publish, empty for the default exchange
1859        :param routing_key: what to publish under
1860        :param message: the message, encoded
1861        :returns: what the broker said
1862        :raises PublishingPausedError: when the broker has blocked this
1863            connection. Nothing was sent; retry once it unblocks
1864        :raises PublishError: when every permit is taken and none came free
1865            within :attr:`confirm_timeout`, or when the broker did not confirm
1866            this publish within it. The second may or may not have arrived
1867        """
1868        # Refused rather than queued, before a permit or a byte is spent. A
1869        # blocked broker stops reading the socket, so a publish sent now sits in
1870        # the client's write buffer with no confirm coming until the alarm
1871        # clears, then times out as a failure that may or may not have arrived.
1872        # Go and .NET refuse at the same point for the same reason. ``None``
1873        # means the state could not be read and is not treated as blocked.
1874        if self.blocked is True:
1875            reason = self.blocked_reason
1876            raise PublishingPausedError(
1877                message.message_id,
1878                exchange,
1879                routing_key,
1880                (
1881                    f"{self._blocked_detail(reason)}. Nothing was sent; back off and "
1882                    "retry once the broker unblocks"
1883                ),
1884            )
1885
1886        # Taken before the message is written and not after, which is the whole
1887        # point: a bound applied afterwards has already let the message into
1888        # memory. The permit is given back in the ``finally`` below on every
1889        # path there is — the publish returning, the publish raising, and this
1890        # task being cancelled while the broker is still thinking — because a
1891        # permit lost on any one of those is a connection that publishes a
1892        # thousand more messages and then stops for ever.
1893        try:
1894            await asyncio.wait_for(
1895                self._outstanding.acquire(), self._confirm_timeout.total_seconds()
1896            )
1897        except asyncio.TimeoutError as stalled:
1898            # Said rather than waited out. A publisher parked behind a broker
1899            # that has stopped answering is indistinguishable from a quiet
1900            # service, and this sentence is the one Java raises word for word so
1901            # that an operator reading a log has one thing to recognise.
1902            raise PublishError(
1903                message.message_id,
1904                exchange,
1905                routing_key,
1906                (
1907                    f"{self._max_outstanding} publishes are already waiting for a "
1908                    f"confirm and none completed within {self._confirm_timeout}. "
1909                    "The broker is not keeping up; publish more slowly rather than "
1910                    "buffering more."
1911                ),
1912            ) from stalled
1913
1914        self._in_flight_publishes += 1
1915        try:
1916            # Bounded as well, by the same timeout. RabbitMQ says a connection is
1917            # blocked only once it publishes, so the first publish after an alarm
1918            # is written and then held with no confirm until the alarm clears --
1919            # minutes, or never. Said here as a failure, not a refusal: it was
1920            # written, so it may have arrived. The publish after it sees the
1921            # block and is refused above. .NET bounds the same wait the same way.
1922            result = await asyncio.wait_for(
1923                self._transport.publish(exchange, routing_key, message),
1924                self._confirm_timeout.total_seconds(),
1925            )
1926        except asyncio.TimeoutError as unconfirmed:
1927            raise PublishError(
1928                message.message_id,
1929                exchange,
1930                routing_key,
1931                (
1932                    f"the broker did not confirm this publish within "
1933                    f"{self._confirm_timeout}. It may or may not have been stored, "
1934                    "so treat it as neither sent nor lost"
1935                ),
1936            ) from unconfirmed
1937        finally:
1938            self._in_flight_publishes -= 1
1939            self._outstanding.release()
1940
1941        # A nack is the broker declining to keep a message it was asked to take, and
1942        # it is raised here rather than returned.
1943        #
1944        # It used to be returned, and `confirmed` was read nowhere in this library
1945        # except a telemetry label -- so a caller who did not inspect the result
1946        # carried on believing the message had gone somewhere, and Java, .NET, Go and
1947        # Ruby all raised on the same event. Worse than the wrong belief: the outbox
1948        # relay removes a record because the publish did not raise, so a nack deleted
1949        # a record for a message the broker had refused. At-most-once, in the pattern
1950        # whose whole purpose is not losing anything.
1951        #
1952        # Checked here because this is the one place every publish in the library
1953        # comes through -- a Publisher, a retry rung, a dead letter, a replay, the
1954        # outbox -- so one check covers all of them, and anything that settles or
1955        # deletes on the strength of a publish returning now hears the refusal.
1956        #
1957        # Distinct from unroutable, which the Publisher path reports separately and
1958        # which sets `unroutable`: the broker could route this one and would not keep
1959        # it, and the two want different responses.
1960        #
1961        # So a returned message is passed back rather than raised here. The
1962        # RabbitMQ transport reports a Basic.Return as not confirmed as well as
1963        # not routed, and raising it as a nack hid ``routed`` from every caller
1964        # that reads it: a mandatory Publisher said "refused" rather than
1965        # "reached no queue", and the retry and dead-letter hops never reached
1966        # the fallbacks written for a queue that is not there.
1967        if not result.confirmed and result.routed:
1968            raise PublishError(
1969                message.message_id,
1970                exchange,
1971                routing_key,
1972                (
1973                    "the broker refused to confirm it. The message reached the broker "
1974                    "and the broker has not taken responsibility for it, so it must be "
1975                    "treated as not sent"
1976                ),
1977            )
1978
1979        return result
1980
1981    async def pull(self, queue: str) -> Delivery | None:
1982        """Takes one message off a queue, or ``None`` when there is none waiting.
1983
1984        For tools rather than for services: it is a round trip per message where
1985        :meth:`consume` gets a stream. What it can do that a consumer cannot is
1986        say that a queue is empty, which is what anything working through a
1987        backlog and then stopping — a replay, a drain — has to know.
1988
1989        The delivery comes back unsettled, so the caller decides whether it is
1990        gone or goes back.
1991
1992        :param queue: what to read from
1993        :returns: the delivery, or ``None``
1994        """
1995        return await self._source().pull(queue)
1996
1997    async def queue_exists(self, queue: str) -> bool:
1998        """Whether a queue is on the broker, creating nothing."""
1999        return await self._admin().queue_exists(queue)
2000
2001    async def message_count(self, queue: str) -> int:
2002        """How many messages are waiting on a queue."""
2003        return await self._admin().message_count(queue)
2004
2005    async def delete_queue(self, queue: str) -> None:
2006        """Removes a queue and every message still on it."""
2007        await self._admin().delete_queue(queue)
2008
2009    def _admin(self) -> QueueAdmin:
2010        if not isinstance(self._transport, QueueAdmin):
2011            raise AceMQError(
2012                f"acemq: the {type(self._transport).__name__} transport cannot manage queues"
2013            )
2014        return self._transport
2015
2016    def _source(self) -> MessageSource:
2017        if not isinstance(self._transport, MessageSource):
2018            raise AceMQError(
2019                f"acemq: the {type(self._transport).__name__} transport cannot be "
2020                "asked for one message at a time"
2021            )
2022        return self._transport
2023
2024    def _untrack(self, consumer: Consumer) -> None:
2025        if consumer in self._consumers:
2026            self._consumers.remove(consumer)
2027
2028    async def close(self, *, timeout: float | None = DEFAULT_DRAIN_TIMEOUT) -> bool:
2029        """Stops every consumer on this connection and releases it.
2030
2031        Consumers first, and their handlers given up to ``timeout`` to finish,
2032        so a message being worked on when this is called is settled rather than
2033        returned to the queue for somebody else to redo. The bound is one
2034        deadline for every handler of every consumer, not one each: they are
2035        all drained at once. A handler still running at the deadline is
2036        cancelled and its message left unsettled, for the broker to redeliver —
2037        see :meth:`Consumer.close`.
2038
2039        The connection is released whatever happens, including when the caller
2040        cancels closing; that cancellation is raised again afterwards.
2041
2042        :param timeout: seconds to wait for the running handlers; ``None``
2043            waits for as long as they take
2044        :returns: ``True`` if every handler finished, ``False`` if the time ran
2045            out first
2046        """
2047        if self._closed:
2048            return True
2049        self._closed = True
2050        try:
2051            drained = await asyncio.gather(
2052                *(consumer.close(timeout=timeout) for consumer in list(self._consumers)),
2053                return_exceptions=True,
2054            )
2055        finally:
2056            await self._transport.close()
2057        for outcome in drained:
2058            if isinstance(outcome, BaseException):
2059                raise outcome
2060        return all(drained)
2061
2062    async def __aenter__(self) -> Connection:
2063        return self
2064
2065    async def __aexit__(self, *_: object) -> None:
2066        await self.close()
2067
2068
2069@dataclass(frozen=True, slots=True)
2070class BrokerHealth:
2071    """A connection as a :class:`~acemq_amqp.telemetry.HealthCheck`.
2072
2073    So that a broker check and an application's own — a database, a downstream
2074    service — can be handed to
2075    :func:`~acemq_amqp.telemetry.aggregate_health` together, which is what a
2076    readiness endpoint actually needs.
2077
2078    A blocked broker comes back through here as **up, with the reason**, and
2079    nothing in between folds it into anything else: the aggregate takes the
2080    worst status it is given, so a check that reported back pressure as degraded
2081    would quietly degrade a report that had decided otherwise. The deadline is
2082    the same argument — :attr:`timeout` is shorter than the aggregate's, so that
2083    a broker which has stopped answering is described by this check rather than
2084    by the aggregate giving up on it.
2085
2086    :param connection: what to ask
2087    :param label: what to call it in a combined report
2088    :param timeout: how long to give the broker's answer. See
2089        :meth:`Connection.health`
2090    """
2091
2092    connection: Connection
2093    label: str = "broker"
2094    timeout: float = DEFAULT_HEALTH_TIMEOUT
2095
2096    @property
2097    def name(self) -> str:
2098        return self.label
2099
2100    async def check(self) -> HealthReport:
2101        return await self.connection.health(self.timeout)
2102
2103
2104async def connect(
2105    url: str,
2106    *,
2107    codec: Codec | None = None,
2108    origin: str | None = None,
2109    retry: RetryPolicy | None = None,
2110    prefetch: int = DEFAULT_PREFETCH,
2111    max_outstanding_publishes: int = DEFAULT_MAX_OUTSTANDING_PUBLISHES,
2112    confirm_timeout: timedelta = DEFAULT_CONFIRM_TIMEOUT,
2113    security: Security | None = None,
2114    on_publish: Sequence[PublishInterceptor] = (),
2115    on_consume: Sequence[ConsumeInterceptor] = (),
2116    observer: Observer | None = None,
2117    **transport_options: Any,
2118) -> Connection:
2119    """Opens a connection to a broker.
2120
2121    The URL's scheme picks the transport, and says whether the connection is
2122    encrypted: ``amqps://`` is, ``amqp://`` is not. Both need aio-pika, which is
2123    why it is imported here rather than by the package: a program that only
2124    reads AceMQ envelopes should not be made to install an AMQP client to import
2125    this library.
2126
2127    An ``amqps://`` URL is verified against the machine's trust store and will
2128    not speak anything older than TLS 1.2, with or without a ``security``. Pass
2129    one to name a different authority, to present a client certificate, or to
2130    supply the login separately from the URL — which is how a password stays out
2131    of a connection string that ends up in a log.
2132
2133    :param url: where the broker is
2134    :param codec: what publishers and consumers use unless they say otherwise
2135    :param origin: what to stamp on published messages
2136    :param retry: what consumers use unless they say otherwise
2137    :param prefetch: how many unacknowledged messages a consumer holds
2138    :param max_outstanding_publishes: how many publishes may be waiting for the
2139        broker at once, a thousand by default. See :class:`Connection`
2140    :param confirm_timeout: how long a publish waits for room before raising
2141    :param security: how to verify the broker and who to log in as. See
2142        :class:`~acemq_amqp.Security`
2143    :param on_publish: what to wrap every publish in, outermost first. See
2144        :mod:`acemq_amqp.interceptors`
2145    :param on_consume: what to wrap every handler in
2146    :param observer: where the numbers go. See :mod:`acemq_amqp.telemetry`
2147    :param transport_options: passed to the transport, which for RabbitMQ is
2148        :func:`aio_pika.connect_robust`
2149    :returns: the connection
2150    :raises SecurityError: when the security settings cannot be honoured, before
2151        anything is dialled
2152    """
2153    scheme = urlsplit(url).scheme
2154    if scheme not in ("amqp", "amqps"):
2155        raise AceMQError(
2156            f"acemq: no transport knows how to reach {scheme or url!r}; "
2157            "this library speaks amqp:// and amqps://"
2158        )
2159
2160    # Resolved here rather than in the transport, so that a missing certificate
2161    # or an unset password variable is an exception from connect() with the
2162    # setting named in it, rather than a handshake failure from somewhere in
2163    # aio-pika that says only that the socket closed.
2164    settings = security or Security()
2165    url = settings.applied_to(url)
2166    # The caller's own options win: transport_options is the escape hatch for
2167    # everything this library does not model, and a Security built from defaults
2168    # should not quietly overrule an ssl_context somebody passed by hand.
2169    transport_options = {**settings.transport_options(url), **transport_options}
2170
2171    try:
2172        from .rabbitmq import RabbitMQTransport
2173    except ImportError as missing:  # pragma: no cover - depends on how it was installed
2174        raise AceMQError(
2175            "acemq: reaching a broker needs aio-pika, which is an optional extra. "
2176            'Install it with pip install "acemq-amqp[rabbitmq]"'
2177        ) from missing
2178
2179    transport = await RabbitMQTransport.connect(url, **transport_options)
2180    return Connection(
2181        transport,
2182        codec=codec,
2183        origin=origin,
2184        retry=retry,
2185        prefetch=prefetch,
2186        max_outstanding_publishes=max_outstanding_publishes,
2187        confirm_timeout=confirm_timeout,
2188        on_publish=on_publish,
2189        on_consume=on_consume,
2190        observer=observer,
2191    )
2192
2193
2194def default_origin() -> str:
2195    """``acemq@{hostname}``, which names the machine but not the service.
2196
2197    Enough to tell two pods apart in a log, which is what an origin is for, and
2198    deliberately not a guess at the service name: a wrong service name in a
2199    message that has already been published is worse than an honest hostname.
2200    """
2201    return f"acemq@{socket.gethostname()}"
2202
2203
2204def _stalled_detail(stalled: list[str]) -> str:
2205    """The sentence naming the consumers that have stopped reading."""
2206    return "these consumers have stopped reading: " + ", ".join(sorted(stalled))
2207
2208
2209def _retrieved(task: asyncio.Task[None]) -> None:
2210    """Reads an abandoned task's outcome so asyncio does not complain about it."""
2211    if not task.cancelled():
2212        task.exception()
2213
2214
2215def _describe(failure: BaseException | None) -> str:
2216    """A failure as the sentence that goes in ``x-acemq-error``."""
2217    if failure is None:
2218        return "no reason given"
2219    text = str(failure)
2220    return type(failure).__name__ + (f": {text}" if text else "")
log = <Logger acemq (WARNING)>
DEFAULT_PREFETCH = 20
DEFAULT_MAX_OUTSTANDING_PUBLISHES = 1000
DEFAULT_CONFIRM_TIMEOUT = datetime.timedelta(seconds=10)
DEFAULT_HEALTH_TIMEOUT = 3.0
DEFAULT_DRAIN_TIMEOUT = 20.0
SET_ASIDE_REFUSED_DELAY = 1.0
BLOCKED_DETAIL = 'the broker has blocked this connection; publishing is paused'
@dataclass(frozen=True, slots=True)
class Message:
179@dataclass(frozen=True, slots=True)
180class Message:
181    """A delivery that has been decoded.
182
183    :param payload: the body, read through the codec
184    :param envelope: the metadata that travelled with it
185    :param routing_key: the key it arrived under
186    :param content_type: what the sender said the body was, or ``None``
187    :param redelivered: the broker saying it has handed this one over before
188    :param body: the undecoded bytes, for a handler that wants to see them
189    :param reply_to: AMQP's own ``reply-to`` property, empty when the sender set
190        none. A responder reads it as the fallback behind the
191        ``acemq-reply-to`` header, which is what lets a Java or .NET caller —
192        neither of which writes the header — be answered by a Python responder
193    """
194
195    payload: Any
196    envelope: Envelope
197    routing_key: str
198    content_type: str | None
199    redelivered: bool
200    body: bytes
201    reply_to: str = ""

A delivery that has been decoded.

Parameters
  • payload: the body, read through the codec
  • envelope: the metadata that travelled with it
  • routing_key: the key it arrived under
  • content_type: what the sender said the body was, or None
  • redelivered: the broker saying it has handed this one over before
  • body: the undecoded bytes, for a handler that wants to see them
  • reply_to: AMQP's own reply-to property, empty when the sender set none. A responder reads it as the fallback behind the acemq-reply-to header, which is what lets a Java or .NET caller — neither of which writes the header — be answered by a Python responder
Message( payload: Any, envelope: acemq_amqp.Envelope, routing_key: str, content_type: str | None, redelivered: bool, body: bytes, reply_to: str = '')
payload: Any
routing_key: str
content_type: str | None
redelivered: bool
body: bytes
reply_to: str
Handler: TypeAlias = Callable[[Message], 'Ack | Awaitable[Ack]']
AsyncHandler: TypeAlias = Callable[[Message], Awaitable[acemq_amqp.Ack]]
class Publisher:
221class Publisher:
222    """Sends messages to one destination.
223
224    Cheap to keep and safe to share: build one per message type at start-up
225    rather than one per message.
226    """
227
228    def __init__(
229        self,
230        connection: Connection,
231        exchange: str,
232        routing_key: str,
233        *,
234        codec: Codec | None = None,
235        persistent: bool = True,
236        mandatory: bool = True,
237    ) -> None:
238        self._connection = connection
239        self._exchange = exchange
240        self._routing_key = routing_key
241        self._codec = codec or connection.codec
242        self._persistent = persistent
243        self._mandatory = mandatory
244
245    async def send(
246        self,
247        payload: Any,
248        *,
249        envelope: Envelope | None = None,
250        routing_key: str | None = None,
251        reply_to: str = "",
252    ) -> PublishResult:
253        """Publishes one message.
254
255        The envelope is built here when none is given: an identifier, a
256        correlation defaulting to it, this connection's origin, and now. The
257        type falls back to the routing key, which is why a publisher bound to
258        ``order.placed`` needs no further configuration to say what it sends.
259
260        :param payload: what to send, encoded by this publisher's codec
261        :param envelope: metadata to send instead of a fresh one, for a message
262            derived from another
263        :param routing_key: what to publish under, for a publisher bound to an
264            exchange rather than to one key
265        :param reply_to: where an answer should come back to, written to AMQP's
266            own ``reply-to`` property. Only :mod:`~acemq_amqp.patterns` request
267            and reply sets it, and it sets the ``acemq-reply-to`` header to the
268            same value: the header is what survives a service that rebuilds the
269            message, the property is what the other four libraries read
270        :returns: what the broker said
271        :raises PublishError: when the publisher is mandatory — the default — and
272            the message reached no queue; its ``unroutable`` is true
273        """
274        key = self._routing_key if routing_key is None else routing_key
275        outgoing = envelope or Envelope(origin=self._connection.origin)
276        if not outgoing.origin:
277            # A message derived from another — a reply, a pipeline hop, the next
278            # stop on a routing slip — is still published by this process, and an
279            # origin naming the service before it would be a lie in a log line
280            # somebody is going to trust.
281            outgoing = outgoing.with_(origin=self._connection.origin)
282
283        context = PublishContext(
284            exchange=self._exchange,
285            routing_key=key,
286            envelope=outgoing,
287            payload=payload,
288            persistent=self._persistent,
289            mandatory=self._mandatory,
290            reply_to=reply_to,
291        )
292        # Read here rather than at construction, so an interceptor registered
293        # during start-up applies to the publishers that already exist. Building
294        # the chain per message costs a few closures and buys that.
295        return await publish_chain(self._connection.publish_interceptors, self._send)(context)
296
297    async def send_all(self, payloads: Iterable[Any]) -> list[PublishResult]:
298        """Publishes a batch and waits for every confirm.
299
300        What most bulk publishing actually wants: the throughput of pipelining
301        with the safety of having waited. Every message goes out before any
302        confirm is awaited, and only then are all of them checked together.
303        Awaiting each send in turn is a broker round trip per message — the
304        loop a caller could have written for themselves, and none of the
305        throughput a batch exists for.
306
307        The results come back in the order the payloads were given, whatever
308        order the broker answers in.
309
310        **This is not atomic.** AMQP has no such thing: there is no way to
311        publish a hundred messages such that all or none arrive, and a library
312        that offered one would be lying. A failure does not abandon the rest
313        either — every send is awaited whatever an earlier one did, so a batch
314        that half succeeded can say how many arrived. That count is the point:
315        a caller told only "it failed" resends the messages the broker already
316        has.
317
318        How wide the batch gets on the wire is capped, and by the connection
319        rather than by this method:
320        :attr:`Connection.max_outstanding_publishes` is a thousand by default,
321        and the thousand-and-first task waits for one of the first thousand to
322        be answered before its message is written. A list of a million is
323        therefore a million tasks and a thousand messages in flight rather than
324        a million, which is backpressure instead of a memory leak — but a
325        million tasks is still a million tasks, so chunk what comes out of a
326        database rather than handing a cursor's worth of rows to one call.
327
328        :param payloads: what to send, in order, each encoded by this
329            publisher's codec
330        :returns: what the broker said about each, in the order the payloads
331            were given
332        :raises PublishError: when any message was not confirmed. Its message
333            names how many failed and how many did not, and ``__cause__``
334            carries the first failure in payload order — which is not
335            necessarily the first one the broker answered. A batch wide enough
336            that the broker stops keeping up fails this way too, with the first
337            failure saying so
338        """
339        batch = list(payloads)
340        # Everything is started before anything is awaited. A task per payload,
341        # all of them created before the gather below, is what puts the whole
342        # batch on the wire while the broker is still working through the
343        # first confirm.
344        sends = [asyncio.create_task(self.send(payload)) for payload in batch]
345        # return_exceptions, and not for tidiness: without it the first failure
346        # comes out of the gather while the rest of the batch is still in
347        # flight, which loses the count this method exists to report and leaves
348        # the others' exceptions unretrieved for asyncio to complain about
349        # later.
350        settled = await asyncio.gather(*sends, return_exceptions=True)
351
352        results: list[PublishResult] = []
353        first_failure: BaseException | None = None
354        failed = 0
355        for outcome in settled:
356            if isinstance(outcome, BaseException):
357                failed += 1
358                if first_failure is None:
359                    first_failure = outcome
360            else:
361                results.append(outcome)
362
363        if first_failure is not None:
364            # Named rather than printed. A failure with nothing in its message —
365            # the CancelledError every task gets when the connection closes
366            # underneath the batch is the common one — renders as an empty
367            # string, and the sentence then ends "The first failure was: " and
368            # stops, promising an explanation it does not give. The class name
369            # is not much, but it is the difference between "the sends were
370            # cancelled" and nothing at all.
371            described = str(first_failure) or type(first_failure).__name__
372            # The counts matter. A batch that half succeeded is the ordinary
373            # outcome of a broker problem partway through, and this sentence is
374            # word for word the one Java and .NET raise, so that an operator
375            # reading a log has one thing to recognise rather than three.
376            raise PublishError(
377                "",
378                self._exchange,
379                self._routing_key,
380                described,
381                summary=(
382                    f"{failed} of {len(batch)} messages were not confirmed;"
383                    f" {len(results)} were. The first failure was: {described}"
384                ),
385            ) from first_failure
386        return results
387
388    async def _send(self, context: PublishContext) -> PublishResult:
389        """The innermost work: encode what the interceptors left, and send it."""
390        observer = self._connection.observer
391        # ``routing.key`` and not ``key``: Java and .NET both tag a publish with
392        # the fully-qualified name, and a dashboard that groups by it should
393        # read the same in all five languages.
394        labels = {TAG_EXCHANGE: context.exchange, TAG_ROUTING_KEY: context.routing_key}
395        # Started before the encode, because everything from here on is time the
396        # caller spends inside send(): the codec, the wait for a permit and the
397        # broker's confirm are all things that make a publish slow, and a timer
398        # that began after the encode would hide a slow codec completely.
399        started = time.monotonic()
400
401        def record(outcome: str) -> None:
402            """The pair, always together and always with the same labels.
403
404            Two calls rather than one because the interface has two methods, and
405            in this order because a dashboard dividing the duration's count into
406            the total should never see the total lead it.
407            """
408            observer.observe(
409                METRIC_PUBLISH_DURATION,
410                time.monotonic() - started,
411                {**labels, TAG_OUTCOME: outcome},
412            )
413            observer.count(METRIC_PUBLISH_TOTAL, 1, {**labels, TAG_OUTCOME: outcome})
414
415        # Encoded here rather than before the chain ran, so an interceptor can
416        # change the payload as well as its metadata. A codec that has already
417        # run leaves an interceptor with bytes and nothing it can do to them.
418        try:
419            body = self._codec.encode(context.payload)
420            result = await self._connection.publish_raw(
421                context.exchange,
422                context.routing_key,
423                Outbound(
424                    body=body,
425                    content_type=self._codec.content_type,
426                    message_id=context.envelope.id,
427                    reply_to=context.reply_to,
428                    headers=context.envelope.to_headers(routing_key=context.routing_key),
429                    persistent=context.persistent,
430                    mandatory=context.mandatory,
431                ),
432            )
433        except PublishingPausedError:
434            # Declined before anything was written: nothing lost, so not
435            # ``failed``, which is the outcome an alert on loss watches.
436            record(OUTCOME_REFUSED)
437            raise
438        except Exception:
439            record(OUTCOME_FAILED)
440            raise
441
442        # Raised rather than left in the result, because a caller who does not
443        # read the result would otherwise carry on believing the message went
444        # somewhere. Unroutable is the quietest failure AMQP has: the publish
445        # succeeds, the consumer waits, and nothing anywhere says why.
446        if context.mandatory and not result.routed:
447            record(OUTCOME_UNROUTABLE)
448            raise PublishError(
449                context.envelope.id,
450                context.exchange,
451                context.routing_key,
452                result.return_reason or "no queue is bound to receive it",
453                unroutable=True,
454            )
455
456        record(OUTCOME_CONFIRMED)
457        return result

Sends messages to one destination.

Cheap to keep and safe to share: build one per message type at start-up rather than one per message.

Publisher( connection: Connection, exchange: str, routing_key: str, *, codec: acemq_amqp.Codec | None = None, persistent: bool = True, mandatory: bool = True)
228    def __init__(
229        self,
230        connection: Connection,
231        exchange: str,
232        routing_key: str,
233        *,
234        codec: Codec | None = None,
235        persistent: bool = True,
236        mandatory: bool = True,
237    ) -> None:
238        self._connection = connection
239        self._exchange = exchange
240        self._routing_key = routing_key
241        self._codec = codec or connection.codec
242        self._persistent = persistent
243        self._mandatory = mandatory
async def send( self, payload: Any, *, envelope: acemq_amqp.Envelope | None = None, routing_key: str | None = None, reply_to: str = '') -> acemq_amqp.PublishResult:
245    async def send(
246        self,
247        payload: Any,
248        *,
249        envelope: Envelope | None = None,
250        routing_key: str | None = None,
251        reply_to: str = "",
252    ) -> PublishResult:
253        """Publishes one message.
254
255        The envelope is built here when none is given: an identifier, a
256        correlation defaulting to it, this connection's origin, and now. The
257        type falls back to the routing key, which is why a publisher bound to
258        ``order.placed`` needs no further configuration to say what it sends.
259
260        :param payload: what to send, encoded by this publisher's codec
261        :param envelope: metadata to send instead of a fresh one, for a message
262            derived from another
263        :param routing_key: what to publish under, for a publisher bound to an
264            exchange rather than to one key
265        :param reply_to: where an answer should come back to, written to AMQP's
266            own ``reply-to`` property. Only :mod:`~acemq_amqp.patterns` request
267            and reply sets it, and it sets the ``acemq-reply-to`` header to the
268            same value: the header is what survives a service that rebuilds the
269            message, the property is what the other four libraries read
270        :returns: what the broker said
271        :raises PublishError: when the publisher is mandatory — the default — and
272            the message reached no queue; its ``unroutable`` is true
273        """
274        key = self._routing_key if routing_key is None else routing_key
275        outgoing = envelope or Envelope(origin=self._connection.origin)
276        if not outgoing.origin:
277            # A message derived from another — a reply, a pipeline hop, the next
278            # stop on a routing slip — is still published by this process, and an
279            # origin naming the service before it would be a lie in a log line
280            # somebody is going to trust.
281            outgoing = outgoing.with_(origin=self._connection.origin)
282
283        context = PublishContext(
284            exchange=self._exchange,
285            routing_key=key,
286            envelope=outgoing,
287            payload=payload,
288            persistent=self._persistent,
289            mandatory=self._mandatory,
290            reply_to=reply_to,
291        )
292        # Read here rather than at construction, so an interceptor registered
293        # during start-up applies to the publishers that already exist. Building
294        # the chain per message costs a few closures and buys that.
295        return await publish_chain(self._connection.publish_interceptors, self._send)(context)

Publishes one message.

The envelope is built here when none is given: an identifier, a correlation defaulting to it, this connection's origin, and now. The type falls back to the routing key, which is why a publisher bound to order.placed needs no further configuration to say what it sends.

Parameters
  • payload: what to send, encoded by this publisher's codec
  • envelope: metadata to send instead of a fresh one, for a message derived from another
  • routing_key: what to publish under, for a publisher bound to an exchange rather than to one key
  • reply_to: where an answer should come back to, written to AMQP's own reply-to property. Only ~acemq_amqp.patterns request and reply sets it, and it sets the acemq-reply-to header to the same value: the header is what survives a service that rebuilds the message, the property is what the other four libraries read :returns: what the broker said
Raises
  • PublishError: when the publisher is mandatory — the default — and the message reached no queue; its unroutable is true
async def send_all( self, payloads: Iterable[typing.Any]) -> list[acemq_amqp.PublishResult]:
297    async def send_all(self, payloads: Iterable[Any]) -> list[PublishResult]:
298        """Publishes a batch and waits for every confirm.
299
300        What most bulk publishing actually wants: the throughput of pipelining
301        with the safety of having waited. Every message goes out before any
302        confirm is awaited, and only then are all of them checked together.
303        Awaiting each send in turn is a broker round trip per message — the
304        loop a caller could have written for themselves, and none of the
305        throughput a batch exists for.
306
307        The results come back in the order the payloads were given, whatever
308        order the broker answers in.
309
310        **This is not atomic.** AMQP has no such thing: there is no way to
311        publish a hundred messages such that all or none arrive, and a library
312        that offered one would be lying. A failure does not abandon the rest
313        either — every send is awaited whatever an earlier one did, so a batch
314        that half succeeded can say how many arrived. That count is the point:
315        a caller told only "it failed" resends the messages the broker already
316        has.
317
318        How wide the batch gets on the wire is capped, and by the connection
319        rather than by this method:
320        :attr:`Connection.max_outstanding_publishes` is a thousand by default,
321        and the thousand-and-first task waits for one of the first thousand to
322        be answered before its message is written. A list of a million is
323        therefore a million tasks and a thousand messages in flight rather than
324        a million, which is backpressure instead of a memory leak — but a
325        million tasks is still a million tasks, so chunk what comes out of a
326        database rather than handing a cursor's worth of rows to one call.
327
328        :param payloads: what to send, in order, each encoded by this
329            publisher's codec
330        :returns: what the broker said about each, in the order the payloads
331            were given
332        :raises PublishError: when any message was not confirmed. Its message
333            names how many failed and how many did not, and ``__cause__``
334            carries the first failure in payload order — which is not
335            necessarily the first one the broker answered. A batch wide enough
336            that the broker stops keeping up fails this way too, with the first
337            failure saying so
338        """
339        batch = list(payloads)
340        # Everything is started before anything is awaited. A task per payload,
341        # all of them created before the gather below, is what puts the whole
342        # batch on the wire while the broker is still working through the
343        # first confirm.
344        sends = [asyncio.create_task(self.send(payload)) for payload in batch]
345        # return_exceptions, and not for tidiness: without it the first failure
346        # comes out of the gather while the rest of the batch is still in
347        # flight, which loses the count this method exists to report and leaves
348        # the others' exceptions unretrieved for asyncio to complain about
349        # later.
350        settled = await asyncio.gather(*sends, return_exceptions=True)
351
352        results: list[PublishResult] = []
353        first_failure: BaseException | None = None
354        failed = 0
355        for outcome in settled:
356            if isinstance(outcome, BaseException):
357                failed += 1
358                if first_failure is None:
359                    first_failure = outcome
360            else:
361                results.append(outcome)
362
363        if first_failure is not None:
364            # Named rather than printed. A failure with nothing in its message —
365            # the CancelledError every task gets when the connection closes
366            # underneath the batch is the common one — renders as an empty
367            # string, and the sentence then ends "The first failure was: " and
368            # stops, promising an explanation it does not give. The class name
369            # is not much, but it is the difference between "the sends were
370            # cancelled" and nothing at all.
371            described = str(first_failure) or type(first_failure).__name__
372            # The counts matter. A batch that half succeeded is the ordinary
373            # outcome of a broker problem partway through, and this sentence is
374            # word for word the one Java and .NET raise, so that an operator
375            # reading a log has one thing to recognise rather than three.
376            raise PublishError(
377                "",
378                self._exchange,
379                self._routing_key,
380                described,
381                summary=(
382                    f"{failed} of {len(batch)} messages were not confirmed;"
383                    f" {len(results)} were. The first failure was: {described}"
384                ),
385            ) from first_failure
386        return results

Publishes a batch and waits for every confirm.

What most bulk publishing actually wants: the throughput of pipelining with the safety of having waited. Every message goes out before any confirm is awaited, and only then are all of them checked together. Awaiting each send in turn is a broker round trip per message — the loop a caller could have written for themselves, and none of the throughput a batch exists for.

The results come back in the order the payloads were given, whatever order the broker answers in.

This is not atomic. AMQP has no such thing: there is no way to publish a hundred messages such that all or none arrive, and a library that offered one would be lying. A failure does not abandon the rest either — every send is awaited whatever an earlier one did, so a batch that half succeeded can say how many arrived. That count is the point: a caller told only "it failed" resends the messages the broker already has.

How wide the batch gets on the wire is capped, and by the connection rather than by this method: Connection.max_outstanding_publishes is a thousand by default, and the thousand-and-first task waits for one of the first thousand to be answered before its message is written. A list of a million is therefore a million tasks and a thousand messages in flight rather than a million, which is backpressure instead of a memory leak — but a million tasks is still a million tasks, so chunk what comes out of a database rather than handing a cursor's worth of rows to one call.

Parameters
  • payloads: what to send, in order, each encoded by this publisher's codec :returns: what the broker said about each, in the order the payloads were given
Raises
  • PublishError: when any message was not confirmed. Its message names how many failed and how many did not, and __cause__ carries the first failure in payload order — which is not necessarily the first one the broker answered. A batch wide enough that the broker stops keeping up fails this way too, with the first failure saying so
class Consumer:
 476class Consumer:
 477    """A running subscription. Close it to stop.
 478
 479    One is built by :meth:`Connection.consume` rather than directly, because it
 480    has to be started before it is any use and a half-built consumer that looks
 481    finished is a thing somebody will hold on to.
 482
 483    Starting one declares the queues it will need when a message fails — its
 484    dead-letter queue, its parking lot and its rungs — unless it was told not
 485    to. See :func:`acemq_amqp.topology.declare_where_failures_go`.
 486    """
 487
 488    def __init__(
 489        self,
 490        connection: Connection,
 491        queue: str,
 492        handler: Handler,
 493        *,
 494        codec: Codec,
 495        retry: RetryPolicy,
 496        concurrency: int,
 497        declare: bool = True,
 498    ) -> None:
 499        if concurrency < 1:
 500            raise ValueError(f"acemq: concurrency must be at least 1, got {concurrency}")
 501        self._connection = connection
 502        self._queue = queue
 503        self._handler = handler
 504        self._codec = codec
 505        self._retry = retry
 506        self._concurrency = concurrency
 507        self._declare = declare
 508        self._work: asyncio.Queue[Delivery | None] = asyncio.Queue()
 509        self._workers: list[asyncio.Task[None]] = []
 510        self._subscription: Subscription | None = None
 511        self._in_flight = 0
 512        self._closed = False
 513        self._halted = False
 514        self._halting: asyncio.Task[bool] | None = None
 515
 516    @property
 517    def queue(self) -> str:
 518        """The queue this consumer reads."""
 519        return self._queue
 520
 521    @property
 522    def closed(self) -> bool:
 523        """Whether this consumer has been stopped."""
 524        return self._closed
 525
 526    @property
 527    def running(self) -> bool:
 528        """Whether this consumer is subscribed and still has workers to hand a
 529        delivery to.
 530
 531        What a health check reads. A consumer whose workers have all finished
 532        without it being closed is a consumer the broker is still sending
 533        messages to and nothing is reading — which looks identical to a quiet
 534        queue from outside, and is the failure worth telling a probe about.
 535        """
 536        return (
 537            not self._closed
 538            and self._subscription is not None
 539            and any(not worker.done() for worker in self._workers)
 540        )
 541
 542    @property
 543    def in_flight(self) -> int:
 544        """How many messages this consumer is working on right now."""
 545        return self._in_flight
 546
 547    @property
 548    def _labels(self) -> dict[str, str]:
 549        return {TAG_QUEUE: self._queue}
 550
 551    @property
 552    def _observer(self) -> Observer:
 553        return self._connection.observer
 554
 555    async def _start(self, prefetch: int, tag: str, args: Mapping[str, Any]) -> None:
 556        if self._declare:
 557            # Before the subscription rather than after it, so that the first
 558            # message this consumer gives up on already has somewhere to go. A
 559            # broker that refuses one of these declarations is a consumer that
 560            # does not start, which is the honest failure: it would otherwise
 561            # start and lose its first dead letter.
 562            await declare_where_failures_go(
 563                self._connection.transport, self._queue, self._retry
 564            )
 565
 566        self._workers = [
 567            asyncio.create_task(self._work_loop(), name=f"acemq-consumer-{self._queue}-{n}")
 568            for n in range(self._concurrency)
 569        ]
 570        try:
 571            self._subscription = await self._connection.transport.consume(
 572                self._queue,
 573                ConsumeSpec(prefetch=prefetch, tag=tag, args=dict(args)),
 574                self._deliver,
 575            )
 576        except BaseException:
 577            # Nothing was subscribed, so nothing will arrive; the workers would
 578            # otherwise sit on an empty queue for the life of the process.
 579            for _ in self._workers:
 580                self._work.put_nowait(None)
 581            await asyncio.gather(*self._workers)
 582            raise
 583
 584    async def _deliver(self, delivery: Delivery) -> None:
 585        """Hands a delivery to the workers.
 586
 587        Queued rather than handled here, so that ``concurrency`` means what it
 588        says: aio-pika starts a task per delivery and does not wait for the last
 589        one, so without a queue of our own a prefetch of twenty would run twenty
 590        handlers at once whatever the caller asked for. The queue needs no bound
 591        because prefetch is one: the broker will not send a twenty-first message
 592        until one of the twenty has been settled.
 593        """
 594        self._work.put_nowait(delivery)
 595
 596    async def _work_loop(self) -> None:
 597        while True:
 598            delivery = await self._work.get()
 599            if delivery is None:
 600                return
 601            try:
 602                await self._handle(delivery)
 603            except Exception:
 604                # A failure here is this library's, not the handler's, and the
 605                # message is left unsettled on purpose: the broker will hand it
 606                # back rather than it disappearing because our own code broke.
 607                log.exception("acemq: could not settle a delivery from %s", self._queue)
 608
 609    async def _handle(self, delivery: Delivery) -> None:
 610        envelope = Envelope.from_headers(
 611            delivery.headers, delivery.routing_key, delivery.message_id
 612        )
 613        # No counter for "a message arrived": every delivery is counted once
 614        # when it is settled, on ``acemq.consume.total`` with the outcome, and
 615        # the sum across the outcomes is how many arrived. One counter that
 616        # leads the others by however many messages are in flight is a counter
 617        # that makes an operator wonder which one is lying.
 618        #
 619        # The attempt is a distribution rather than a counter, and it is recorded
 620        # here on arrival rather than at the settlement: it is a fact about the
 621        # delivery that is true before the handler runs, and recording it after
 622        # would drop every message this consumer is still working on when the
 623        # process stops. A rising distribution is a dependency in trouble, and it
 624        # says so before anything else does — the dead letters only move once the
 625        # attempts run out.
 626        self._observer.observe(
 627            METRIC_CONSUME_ATTEMPTS, float(envelope.attempt), self._labels
 628        )
 629        self._in_flight += 1
 630        self._observer.gauge(METRIC_CONSUME_IN_FLIGHT, self._in_flight, self._labels)
 631        try:
 632            await self._handle_one(delivery, envelope)
 633        finally:
 634            self._in_flight -= 1
 635            self._observer.gauge(METRIC_CONSUME_IN_FLIGHT, self._in_flight, self._labels)
 636
 637    async def _handle_one(self, delivery: Delivery, envelope: Envelope) -> None:
 638        if self._halted:
 639            # Prefetched before the reader stopped. Returned unhandled: nothing
 640            # after the message it stopped at is handled.
 641            await delivery.nack(True)
 642            return
 643        try:
 644            payload = self._codec.decode(delivery.body, delivery.content_type)
 645        except Exception as failure:
 646            # A body that will not decode decodes no better next time, so it
 647            # does not go round the retry schedule until it ages out.
 648            #
 649            # Parked rather than dead-lettered: a message that failed five times
 650            # and a message nothing could read are different problems with
 651            # different answers — one is usually the world, the other is usually
 652            # a producer — and whoever drains the dead letters should not have
 653            # to sort them by hand.
 654            #
 655            # Counted as a settled delivery here rather than in ``_carry_out``,
 656            # which this path never reaches: no handler ran, so there is no
 657            # duration to record, but the message did arrive and was dealt with
 658            # and a total that missed it would not add up.
 659            self._observer.count(
 660                METRIC_CONSUME_TOTAL, 1, {**self._labels, TAG_OUTCOME: OUTCOME_PARKED}
 661            )
 662            await self._park(
 663                delivery, envelope, f"could not be decoded: {_describe(failure)}"
 664            )
 665            return
 666
 667        context = ConsumeContext(
 668            queue=self._queue,
 669            envelope=envelope,
 670            payload=payload,
 671            body=delivery.body,
 672            content_type=delivery.content_type,
 673            routing_key=delivery.routing_key,
 674            redelivered=delivery.redelivered,
 675            # This delivery is being driven by a consumer, so how it ends will
 676            # be reported. An interceptor that wants to know can wait for it.
 677            reports_settlement=True,
 678            reply_to=delivery.reply_to,
 679        )
 680
 681        started = time.monotonic()
 682        try:
 683            decision = await consume_chain(
 684                self._connection.consume_interceptors, self._run_handler
 685            )(context)
 686        except Exception as failure:
 687            # An exception is how Python says a thing failed, so a handler that
 688            # raises is asking for the retry policy rather than confessing a
 689            # bug — which is what Java does with the same situation, and what a
 690            # handler written without reading the documentation will expect.
 691            # Raising FatalError is how it says the opposite, and the retry path
 692            # below reads that mark before it reads the request.
 693            #
 694            # An interceptor that raises lands here too, and deliberately: a
 695            # refused message is retried and then dead-lettered rather than
 696            # acknowledged as though something had processed it.
 697            decision = Ack(Action.RETRY, failure)
 698
 699        # Timed around the interceptors as well as the handler, because what an
 700        # operator wants to know is how long a message takes to deal with, and
 701        # an interceptor that opens a transaction is part of dealing with it.
 702        # Stopped here and recorded a few lines below rather than in a
 703        # ``finally``, because the duration is tagged with the outcome and the
 704        # outcome is not known until ``_decide`` has run: how long a message
 705        # took and what happened to it are one question, and a p99 that mixes
 706        # the messages that worked with the ones that timed out answers neither
 707        # half of it.
 708        elapsed = time.monotonic() - started
 709
 710        # Whatever the interceptors left, rather than what arrived: one that
 711        # rewrote the envelope on the way in meant that rewrite for the retry
 712        # and the dead letter as much as for the handler.
 713        envelope = context.envelope
 714
 715        if isinstance(decision, Ack):
 716            settlement, wait = self._decide(envelope, decision)
 717        else:
 718            settlement, wait = (
 719                Settlement(
 720                    OUTCOME_DEAD_LETTERED,
 721                    reason=(
 722                        f"the handler returned {type(decision).__name__} instead of an Ack"
 723                    ),
 724                ),
 725                None,
 726            )
 727
 728        self._observer.observe(
 729            METRIC_CONSUME_DURATION,
 730            elapsed,
 731            {**self._labels, TAG_OUTCOME: settlement.outcome},
 732        )
 733
 734        # Announced before it is carried out, and so before a consumer-side
 735        # retry sleeps out its backoff. A listener told afterwards would be
 736        # describing the delivery minutes after the decision, and the span it is
 737        # writing on would have stayed open for a wait that is not work.
 738        context.settled(settlement)
 739        await self._carry_out(delivery, envelope, settlement, wait)
 740
 741    async def _run_handler(self, context: ConsumeContext) -> Ack:
 742        """The innermost work: build the message the interceptors left, and run
 743        the handler on it.
 744
 745        The message is built here rather than before the chain, so that an
 746        interceptor which changed the envelope or the payload changed what the
 747        handler is given rather than a copy nobody reads.
 748        """
 749        message = Message(
 750            payload=context.payload,
 751            envelope=context.envelope,
 752            routing_key=context.routing_key,
 753            content_type=context.content_type,
 754            redelivered=context.redelivered,
 755            body=context.body,
 756            reply_to=context.reply_to,
 757        )
 758        returned = self._handler(message)
 759        # Not an Ack is a mistake worth reporting, but it is not this method's
 760        # to report: it is returned as it stands and _handle dead-letters it
 761        # with a reason, which is where every other unhandleable delivery goes.
 762        # An interceptor between here and there sees the same thing the handler
 763        # returned, which is the honest thing to show it.
 764        decision: Ack = await returned if inspect.isawaitable(returned) else returned
 765        return decision
 766
 767    def _decide(self, envelope: Envelope, decision: Ack) -> tuple[Settlement, Wait | None]:
 768        """What is going to happen to this delivery, before anything happens to
 769        it.
 770
 771        Worked out on its own, and without touching the broker, so that it can
 772        be announced first. The gap this closes is a small one to describe and a
 773        wide one to fall into: a handler asking for a retry it has no attempts
 774        left for is dead-lettered, and anything reading the handler's answer
 775        instead of this one records a retry that never happened.
 776
 777        :param envelope: the message's metadata, for the attempt and the age
 778        :param decision: what the handler answered
 779        :returns: the settlement, and the wait when there is another attempt —
 780            which the settlement does not carry, because whether a wait is spent
 781            here or on a rung queue is this consumer's business and not a
 782            listener's
 783        """
 784        if decision.action is Action.ACCEPT:
 785            return Settlement(OUTCOME_ACKED), None
 786
 787        if decision.action is Action.REJECT:
 788            return (
 789                Settlement(
 790                    OUTCOME_REJECTED,
 791                    reason=f"the handler rejected it: {_describe(decision.error)}",
 792                ),
 793                None,
 794            )
 795
 796        if decision.action is Action.PARK:
 797            # The handler read the message and found nothing it could read. The
 798            # engine reaches the same conclusion for a body its codec refuses,
 799            # and both end up in the same queue for the same reason: a message
 800            # nobody can read is a producer problem, and it is only findable if
 801            # it is not filed with the messages that merely ran out of luck.
 802            return (
 803                Settlement(
 804                    OUTCOME_PARKED,
 805                    reason=f"the handler parked it: {_describe(decision.error)}",
 806                ),
 807                None,
 808            )
 809
 810        if decision.action is Action.IN_PROGRESS:
 811            # Somebody else holds the message. Not a failure of this one, so the
 812            # retry policy is not asked: it can neither spend an attempt nor run
 813            # out and dead-letter a message nobody has failed to handle.
 814            delay = decision.delay if decision.delay is not None else ZERO
 815            return Settlement(OUTCOME_IN_PROGRESS, delay=delay), Wait(delay, in_broker=False)
 816
 817        if isinstance(decision.error, _StopReadingError):
 818            return (
 819                Settlement(
 820                    OUTCOME_STOPPED,
 821                    reason=f"the reader stopped at it: {_describe(decision.error)}",
 822                ),
 823                None,
 824            )
 825
 826        if isinstance(decision.error, FatalError):
 827            # The handler asked for a retry but marked the reason as one that
 828            # will not change. Honouring the mark rather than the request is the
 829            # point of having it.
 830            return (
 831                Settlement(
 832                    OUTCOME_DEAD_LETTERED,
 833                    reason=(
 834                        "the handler reported an unprocessable message: "
 835                        f"{_describe(decision.error)}"
 836                    ),
 837                ),
 838                None,
 839            )
 840
 841        wait = self._retry.next_wait(envelope.attempt, envelope.age)
 842        if wait is None:
 843            return (
 844                Settlement(
 845                    OUTCOME_DEAD_LETTERED,
 846                    reason=f"{self._exhausted(envelope)}: {_describe(decision.error)}",
 847                ),
 848                None,
 849            )
 850
 851        return Settlement(OUTCOME_RETRIED, delay=wait.delay), wait
 852
 853    async def _carry_out(
 854        self,
 855        delivery: Delivery,
 856        envelope: Envelope,
 857        settlement: Settlement,
 858        wait: Wait | None,
 859    ) -> None:
 860        """Does what :meth:`_decide` decided, and counts it as decided.
 861
 862        Every counter here is chosen from the :class:`~acemq_amqp.ack.Settlement`
 863        and never from the handler's :class:`~acemq_amqp.ack.Ack`, which is the
 864        same rule the delivery's span follows. A handler asking for a retry it
 865        has no attempts left for is dead-lettered, and a counter that read the
 866        request rather than the answer would report a retry for a message
 867        nothing will ever try again — so the dead letters would be undercounted
 868        by exactly the messages an operator most wants to find.
 869
 870        One ``acemq.consume.total`` per delivery, carrying the outcome, and then
 871        whichever of the standalone counters applies. ``retried`` and
 872        ``dead_lettered`` are both an outcome here and a counter of their own,
 873        which is what Java does and is not a redundancy: the outcome says what
 874        was decided about a delivery, and the counter says how many messages are
 875        going round again or have been set aside, which is the number an alert
 876        is written against.
 877        """
 878        self._observer.count(
 879            METRIC_CONSUME_TOTAL, 1, {**self._labels, TAG_OUTCOME: settlement.outcome}
 880        )
 881
 882        if settlement.outcome == OUTCOME_ACKED:
 883            await delivery.ack()
 884            return
 885
 886        if settlement.outcome == OUTCOME_STOPPED:
 887            # Returned, not acknowledged: on a stream neither moves the log, and
 888            # a requeue is the honest word for a message nothing has dealt with.
 889            log.error(
 890                "acemq: stopped reading %s at %s: %s",
 891                self._queue,
 892                envelope.id,
 893                settlement.reason,
 894            )
 895            self._halt()
 896            await delivery.nack(True)
 897            return
 898
 899        if settlement.outcome == OUTCOME_PARKED:
 900            # ``_park`` counts it, exactly as it does for a body that would not
 901            # decode. There is one parked counter and one parked queue whether
 902            # the codec or the handler was the one that could not read it.
 903            await self._park(delivery, envelope, settlement.reason or "")
 904            return
 905
 906        if wait is None:
 907            await self._dead_letter(delivery, envelope, settlement.reason or "")
 908            return
 909
 910        if settlement.outcome == OUTCOME_IN_PROGRESS:
 911            await self._put_back(delivery, envelope, wait.delay)
 912            return
 913
 914        if wait.in_broker and await self._retry_in_broker(delivery, envelope, wait.delay):
 915            return
 916
 917        if wait.delay > ZERO:
 918            # Waiting here holds the delivery, and so holds one of this
 919            # consumer's prefetch slots. For a wait of a few seconds that is the
 920            # cheaper of the two costs; for a longer one it is not, which is why
 921            # the policy has a threshold and the long waits went to a rung queue
 922            # a few lines above.
 923            await asyncio.sleep(wait.delay.total_seconds())
 924
 925        await self._retry_again(delivery, envelope, wait.delay)
 926
 927    def _exhausted(self, envelope: Envelope) -> str:
 928        """Why there is no next attempt, in words an operator can act on."""
 929        if envelope.attempt >= self._retry.max_attempts:
 930            attempts = self._retry.max_attempts
 931            return f"exhausted {attempts} attempt{'' if attempts == 1 else 's'}"
 932        return f"exceeded the maximum message age of {self._retry.max_message_age}"
 933
 934    async def _retry_in_broker(
 935        self, delivery: Delivery, envelope: Envelope, delay: timedelta
 936    ) -> bool:
 937        """Parks the message on ``{queue}.retry.{delay}`` and lets the broker
 938        return it.
 939
 940        The rung's ``x-message-ttl`` is the delay and its dead-letter target is
 941        this queue, so the wait costs nothing here: no delivery held, no prefetch
 942        slot spent, and — the reason it exists — nothing lost when this process
 943        restarts halfway through. A consumer sleeping on a five-minute backoff
 944        that dies at minute one does not resume at minute one; the broker
 945        redelivers the unacknowledged message immediately, and the policy that
 946        said five minutes delivers in none.
 947
 948        The obvious simplification is one rung queue and a per-message
 949        ``expiration`` instead of several with fixed TTLs. It does not work.
 950        RabbitMQ only ever expires the message at the *head* of a queue, so a
 951        message with a ten-minute TTL at the front holds back every thirty-second
 952        one behind it, and the delays that come out bear no resemblance to the
 953        ones that went in. Never set a per-message TTL for this.
 954
 955        The attempt advances here exactly as it does on an immediate retry: the
 956        counter belongs to the message, and a message that has been round the
 957        broker is no less on its second attempt than one that waited here.
 958
 959        :returns: whether the rung took it. ``False`` means no such queue, and
 960            the caller should fall back to waiting here
 961        """
 962        rung = naming.retry_queue(self._queue, delay)
 963        next_attempt = envelope.with_(attempt=envelope.attempt + 1)
 964        try:
 965            routed = await self._republish(delivery, rung, next_attempt)
 966        except _HopRefusedError:
 967            # The rung is there and would not take it. Requeued at once, with
 968            # nothing else on this consumer settled, rather than waited out
 969            # here: the broker is the one saying no, and holding the delivery
 970            # for the whole delay would stall this consumer for nothing.
 971            self._observer.count(METRIC_RETRIED_TOTAL, 1, {**self._labels, "where": "requeued"})
 972            await delivery.nack(True)
 973            return True
 974        if not routed:
 975            # Kept even though a consumer declares its own rungs when it starts,
 976            # because the rung can still be missing: a consumer started with
 977            # ``declare=False`` declares nothing, and a rung deleted under a
 978            # running consumer is gone whoever declared it. What has changed is
 979            # what it means — it used to be an ordinary topology mistake and is
 980            # now either a deliberate opt-out or somebody removing queues.
 981            #
 982            # Degraded rather than fatal: the message is still deliverable, and
 983            # waiting for it here is what this library did before there were
 984            # rungs. Counted as well as logged, because this is the one failure
 985            # here that nothing else shows: the message is still retried and the
 986            # wait still happens, so a dashboard reads as normal while the reason
 987            # the rung exists is quietly gone.
 988            self._observer.count(METRIC_RUNG_MISSING, 1, {**self._labels, "rung": rung})
 989            log.error(
 990                "acemq: %s is not on the broker, so %s will wait %s in this consumer "
 991                "instead; declare it with Topology().queue(%r, retry=policy), or let "
 992                "the consumer declare it by leaving declare=True",
 993                rung,
 994                envelope.id,
 995                delay,
 996                self._queue,
 997            )
 998            return False
 999
1000        self._observer.count(METRIC_RETRIED_TOTAL, 1, {**self._labels, "where": "broker"})
1001        log.info(
1002            "acemq: retrying %s from %s, attempt %d of %d, after %s in %s",
1003            envelope.id,
1004            self._queue,
1005            next_attempt.attempt,
1006            self._retry.max_attempts,
1007            delay,
1008            rung,
1009        )
1010        await delivery.ack()
1011        return True
1012
1013    async def _retry_again(
1014        self, delivery: Delivery, envelope: Envelope, delay: timedelta
1015    ) -> None:
1016        """Puts the message back on its own queue, one attempt further on.
1017
1018        Republished rather than requeued, because a requeue returns the bytes
1019        the broker was given: the attempt header would still read what the
1020        publisher wrote however many times the message had come round, and the
1021        count would live only in this process's memory, which is the one place
1022        it is lost when the process that has been failing restarts.
1023
1024        The cost is that the message goes to the back of the queue rather than
1025        the front, so a retry is no longer in order with its neighbours. For a
1026        message that has already failed once, that is the better trade.
1027        """
1028        next_attempt = envelope.with_(attempt=envelope.attempt + 1)
1029        try:
1030            delivered = await self._republish(delivery, self._queue, next_attempt)
1031        except _HopRefusedError:
1032            delivered = False
1033        if not delivered:
1034            # The queue we are consuming has gone. Requeued rather than
1035            # acknowledged, because dropping it here would lose a message over a
1036            # broker change nobody told this consumer about.
1037            #
1038            # Counted as a retry all the same, and it is one: the settlement
1039            # said ``retried``, the span says ``retried``, and the broker is
1040            # about to hand the message back. Leaving it uncounted was the one
1041            # place where the counters and the span disagreed about the same
1042            # delivery. The label says which path it took, because a requeue
1043            # keeps the attempt header it arrived with and the other two do not.
1044            self._observer.count(METRIC_RETRIED_TOTAL, 1, {**self._labels, "where": "requeued"})
1045            log.error(
1046                "acemq: cannot republish %s onto %s for attempt %d; returning it to the broker",
1047                envelope.id,
1048                self._queue,
1049                next_attempt.attempt,
1050            )
1051            await delivery.nack(True)
1052            return
1053
1054        self._observer.count(METRIC_RETRIED_TOTAL, 1, {**self._labels, "where": "consumer"})
1055        log.info(
1056            "acemq: retrying %s from %s, attempt %d of %d, after %s",
1057            envelope.id,
1058            self._queue,
1059            next_attempt.attempt,
1060            self._retry.max_attempts,
1061            delay,
1062        )
1063        await delivery.ack()
1064
1065    async def _put_back(
1066        self, delivery: Delivery, envelope: Envelope, delay: timedelta
1067    ) -> None:
1068        """Returns a message somebody else is working on, attempt unchanged.
1069
1070        :meth:`_retry_again` without the increment: the attempt counts this
1071        message's failures, and a claim held elsewhere is not one of them.
1072        """
1073        if delay > ZERO:
1074            await asyncio.sleep(delay.total_seconds())
1075        try:
1076            delivered = await self._republish(delivery, self._queue, envelope)
1077        except _HopRefusedError:
1078            delivered = False
1079        if delivered:
1080            await delivery.ack()
1081            return
1082        log.error(
1083            "acemq: cannot put %s back onto %s; returning it to the broker",
1084            envelope.id,
1085            self._queue,
1086        )
1087        await delivery.nack(True)
1088
1089    async def _park(self, delivery: Delivery, envelope: Envelope, reason: str) -> None:
1090        """Sends the message to ``{queue}.parked`` with the reason attached.
1091
1092        Where a message goes when it never reached the handler at all. Somebody
1093        has to look at it, and what they need to know first is that it was
1094        unreadable rather than unlucky.
1095        """
1096        # The same counter a dead-lettering moves, separated by the outcome
1097        # rather than by a metric of its own — which is what Java settled on, and
1098        # what makes "how much is this queue giving up on" one number that can
1099        # then be split into the two problems it is made of.
1100        self._observer.count(
1101            METRIC_DEAD_LETTERED_TOTAL, 1, {**self._labels, TAG_OUTCOME: OUTCOME_PARKED}
1102        )
1103        await self._set_aside(delivery, envelope, naming.parked_queue(self._queue), reason)
1104
1105    async def _dead_letter(self, delivery: Delivery, envelope: Envelope, reason: str) -> None:
1106        """Sends the message to ``{queue}.dlq`` with the reason attached, and
1107        acknowledges the original.
1108
1109        Acknowledging a message that failed looks wrong and is what makes this
1110        reliable: the message has already been safely republished somewhere
1111        else, so acknowledging the original is removing the copy that has been
1112        dealt with. Rejecting it instead would either requeue it into a hot loop
1113        or, with a dead-letter exchange configured on the queue, send it
1114        somewhere this consumer did not choose and without the reason.
1115
1116        The reason travels as an envelope field, so a consumer of the
1117        dead-letter queue reads it back through the API rather than having to
1118        know the wire header name.
1119        """
1120        self._observer.count(
1121            METRIC_DEAD_LETTERED_TOTAL,
1122            1,
1123            {**self._labels, TAG_OUTCOME: OUTCOME_DEAD_LETTERED},
1124        )
1125        await self._set_aside(
1126            delivery, envelope, naming.dead_letter_queue(self._queue), reason
1127        )
1128
1129    async def _set_aside(
1130        self, delivery: Delivery, envelope: Envelope, target: str, reason: str
1131    ) -> None:
1132        """Republishes to ``target`` with the reason, then acknowledges."""
1133        failed = envelope.with_(error=reason)
1134        try:
1135            delivered = await self._republish(delivery, target, failed)
1136        except _HopRefusedError:
1137            delivered = False
1138        if not delivered:
1139            # Requeued, never rejected (AceMQ TCK requirements AMQP-PUB-002 and
1140            # AMQP-RETRY-007). Rejecting without requeue dropped the message, or
1141            # dead-lettered it through the source queue's own dead-letter
1142            # exchange somewhere it does not belong, the moment the broker
1143            # refused the copy. Requeued, it comes back and is set aside again
1144            # once the broker takes it.
1145            self._observer.count(
1146                METRIC_SET_ASIDE_FAILED, 1, {**self._labels, TAG_TARGET: target}
1147            )
1148            log.error(
1149                "acemq: cannot move %s to %s (%s); returning it to the broker",
1150                envelope.id,
1151                target,
1152                reason,
1153            )
1154            await asyncio.sleep(SET_ASIDE_REFUSED_DELAY)
1155            await delivery.nack(True)
1156            return
1157
1158        log.warning(
1159            "acemq: set aside %s from %s after %d attempts, into %s: %s",
1160            envelope.id,
1161            self._queue,
1162            envelope.attempt,
1163            target,
1164            reason,
1165        )
1166        await delivery.ack()
1167
1168    async def _republish(self, delivery: Delivery, queue: str, envelope: Envelope) -> bool:
1169        """Sends the original bytes to a queue by name, and says whether they
1170        arrived.
1171
1172        Through the default exchange, which routes to the queue whose name
1173        matches the routing key, and mandatory so that a queue that is not there
1174        is an answer rather than a silence. The body goes back exactly as it
1175        came: re-encoding through a class that has since changed would replace
1176        what was committed with something else.
1177        """
1178        try:
1179            result = await self._connection.publish_raw(
1180                "",
1181                queue,
1182                Outbound(
1183                    body=delivery.body,
1184                    content_type=delivery.content_type or "",
1185                    message_id=envelope.id,
1186                    headers=envelope.to_headers(routing_key=delivery.routing_key),
1187                    persistent=True,
1188                    mandatory=True,
1189                ),
1190            )
1191        except PublishError as refused:
1192            # The broker nacked it, or would not take it while blocked. Raised
1193            # as the caller's to settle, because what to do differs: a refused
1194            # rung means requeue now, where a missing rung means wait here.
1195            # Escaping further left the delivery unsettled for the life of the
1196            # channel, which is what Ruby did before 0.7.12.
1197            log.error("acemq: the broker refused %s onto %s: %s", envelope.id, queue, refused)
1198            raise _HopRefusedError(str(refused)) from refused
1199        return result.routed
1200
1201    def _halt(self) -> None:
1202        """Stops this consumer from inside one of its own handlers.
1203
1204        The close runs as a task of its own, because it waits for the workers
1205        and the caller is one of them.
1206        """
1207        self._halted = True
1208        if self._halting is None:
1209            self._halting = asyncio.get_running_loop().create_task(self.close())
1210
1211    async def close(self, *, timeout: float | None = DEFAULT_DRAIN_TIMEOUT) -> bool:
1212        """Stops the consumer and waits, for up to ``timeout``, for the handlers
1213        already running.
1214
1215        A message being worked on when this is called is finished and settled,
1216        rather than abandoned for the broker to hand to somebody else. A message
1217        that had been delivered but not started is given back instead: it is the
1218        broker's to hand to another consumer, and holding it here only to work
1219        through a retry delay would make closing take as long as the schedule.
1220
1221        A handler still running when the time is up is cancelled, and its message
1222        is left unsettled — neither acknowledged nor rejected — so the broker
1223        hands it out again once the channel goes. Shutdown is never the reason a
1224        message is lost or dead-lettered. The same happens when the caller
1225        cancels closing, ``asyncio.wait_for`` included, and that cancellation is
1226        raised again once the consumer has been cleaned up.
1227
1228        The subscription is released last, after everything has been settled,
1229        because a settlement travels on the channel its delivery arrived on.
1230
1231        :param timeout: seconds to wait for every running handler together;
1232            ``None`` waits for as long as they take
1233        :returns: ``True`` if every handler finished, ``False`` if the time ran
1234            out first and some were cut off — the consumer is stopped either way
1235        """
1236        if self._closed:
1237            halting = self._halting
1238            if halting is not None and halting is not asyncio.current_task():
1239                # Stopped by its own handler and still closing: closing the
1240                # connection underneath that would cut it off halfway.
1241                return await halting
1242            return True
1243        self._closed = True
1244
1245        running: set[asyncio.Task[None]] = set()
1246        try:
1247            if self._subscription is not None:
1248                await self._subscription.stop()
1249
1250            while True:
1251                try:
1252                    pending = self._work.get_nowait()
1253                except asyncio.QueueEmpty:
1254                    break
1255                if pending is not None:
1256                    await pending.nack(True)
1257
1258            for _ in self._workers:
1259                self._work.put_nowait(None)
1260            if self._workers:
1261                _, running = await asyncio.wait(self._workers, timeout=timeout)
1262        finally:
1263            # Reached with workers still running for two reasons: the deadline
1264            # passed, or the caller cancelled us. Either way they are cancelled
1265            # before the channel goes, so nothing settles a message on a channel
1266            # that is closing — and a cancellation that came from the caller is
1267            # not caught here, so it carries on out once this has run.
1268            stragglers = [worker for worker in self._workers if not worker.done()]
1269            for worker in stragglers:
1270                worker.cancel()
1271            if stragglers:
1272                await asyncio.wait(stragglers)
1273            if self._subscription is not None:
1274                await self._subscription.close()
1275            self._connection._untrack(self)
1276
1277        for worker in self._workers:
1278            # A worker that was already cancelled — a task group unwinding, a
1279            # shutdown that cancelled the loop's tasks before closing the
1280            # connection — is not news to report to a caller who is merely
1281            # closing. One that died of its own accord is.
1282            failure = None if worker.cancelled() else worker.exception()
1283            if failure is not None:
1284                raise failure
1285        return not running
1286
1287    async def __aenter__(self) -> Consumer:
1288        return self
1289
1290    async def __aexit__(self, *_: object) -> None:
1291        # Not returned: a true value from here tells the interpreter that the
1292        # exception leaving the block was handled.
1293        await self.close()

A running subscription. Close it to stop.

One is built by Connection.consume() rather than directly, because it has to be started before it is any use and a half-built consumer that looks finished is a thing somebody will hold on to.

Starting one declares the queues it will need when a message fails — its dead-letter queue, its parking lot and its rungs — unless it was told not to. See acemq_amqp.topology.declare_where_failures_go().

Consumer( connection: Connection, queue: str, handler: Callable[Message, acemq_amqp.Ack | Awaitable[acemq_amqp.Ack]], *, codec: acemq_amqp.Codec, retry: acemq_amqp.RetryPolicy, concurrency: int, declare: bool = True)
488    def __init__(
489        self,
490        connection: Connection,
491        queue: str,
492        handler: Handler,
493        *,
494        codec: Codec,
495        retry: RetryPolicy,
496        concurrency: int,
497        declare: bool = True,
498    ) -> None:
499        if concurrency < 1:
500            raise ValueError(f"acemq: concurrency must be at least 1, got {concurrency}")
501        self._connection = connection
502        self._queue = queue
503        self._handler = handler
504        self._codec = codec
505        self._retry = retry
506        self._concurrency = concurrency
507        self._declare = declare
508        self._work: asyncio.Queue[Delivery | None] = asyncio.Queue()
509        self._workers: list[asyncio.Task[None]] = []
510        self._subscription: Subscription | None = None
511        self._in_flight = 0
512        self._closed = False
513        self._halted = False
514        self._halting: asyncio.Task[bool] | None = None
queue: str
516    @property
517    def queue(self) -> str:
518        """The queue this consumer reads."""
519        return self._queue

The queue this consumer reads.

closed: bool
521    @property
522    def closed(self) -> bool:
523        """Whether this consumer has been stopped."""
524        return self._closed

Whether this consumer has been stopped.

running: bool
526    @property
527    def running(self) -> bool:
528        """Whether this consumer is subscribed and still has workers to hand a
529        delivery to.
530
531        What a health check reads. A consumer whose workers have all finished
532        without it being closed is a consumer the broker is still sending
533        messages to and nothing is reading — which looks identical to a quiet
534        queue from outside, and is the failure worth telling a probe about.
535        """
536        return (
537            not self._closed
538            and self._subscription is not None
539            and any(not worker.done() for worker in self._workers)
540        )

Whether this consumer is subscribed and still has workers to hand a delivery to.

What a health check reads. A consumer whose workers have all finished without it being closed is a consumer the broker is still sending messages to and nothing is reading — which looks identical to a quiet queue from outside, and is the failure worth telling a probe about.

in_flight: int
542    @property
543    def in_flight(self) -> int:
544        """How many messages this consumer is working on right now."""
545        return self._in_flight

How many messages this consumer is working on right now.

async def close(self, *, timeout: float | None = 20.0) -> bool:
1211    async def close(self, *, timeout: float | None = DEFAULT_DRAIN_TIMEOUT) -> bool:
1212        """Stops the consumer and waits, for up to ``timeout``, for the handlers
1213        already running.
1214
1215        A message being worked on when this is called is finished and settled,
1216        rather than abandoned for the broker to hand to somebody else. A message
1217        that had been delivered but not started is given back instead: it is the
1218        broker's to hand to another consumer, and holding it here only to work
1219        through a retry delay would make closing take as long as the schedule.
1220
1221        A handler still running when the time is up is cancelled, and its message
1222        is left unsettled — neither acknowledged nor rejected — so the broker
1223        hands it out again once the channel goes. Shutdown is never the reason a
1224        message is lost or dead-lettered. The same happens when the caller
1225        cancels closing, ``asyncio.wait_for`` included, and that cancellation is
1226        raised again once the consumer has been cleaned up.
1227
1228        The subscription is released last, after everything has been settled,
1229        because a settlement travels on the channel its delivery arrived on.
1230
1231        :param timeout: seconds to wait for every running handler together;
1232            ``None`` waits for as long as they take
1233        :returns: ``True`` if every handler finished, ``False`` if the time ran
1234            out first and some were cut off — the consumer is stopped either way
1235        """
1236        if self._closed:
1237            halting = self._halting
1238            if halting is not None and halting is not asyncio.current_task():
1239                # Stopped by its own handler and still closing: closing the
1240                # connection underneath that would cut it off halfway.
1241                return await halting
1242            return True
1243        self._closed = True
1244
1245        running: set[asyncio.Task[None]] = set()
1246        try:
1247            if self._subscription is not None:
1248                await self._subscription.stop()
1249
1250            while True:
1251                try:
1252                    pending = self._work.get_nowait()
1253                except asyncio.QueueEmpty:
1254                    break
1255                if pending is not None:
1256                    await pending.nack(True)
1257
1258            for _ in self._workers:
1259                self._work.put_nowait(None)
1260            if self._workers:
1261                _, running = await asyncio.wait(self._workers, timeout=timeout)
1262        finally:
1263            # Reached with workers still running for two reasons: the deadline
1264            # passed, or the caller cancelled us. Either way they are cancelled
1265            # before the channel goes, so nothing settles a message on a channel
1266            # that is closing — and a cancellation that came from the caller is
1267            # not caught here, so it carries on out once this has run.
1268            stragglers = [worker for worker in self._workers if not worker.done()]
1269            for worker in stragglers:
1270                worker.cancel()
1271            if stragglers:
1272                await asyncio.wait(stragglers)
1273            if self._subscription is not None:
1274                await self._subscription.close()
1275            self._connection._untrack(self)
1276
1277        for worker in self._workers:
1278            # A worker that was already cancelled — a task group unwinding, a
1279            # shutdown that cancelled the loop's tasks before closing the
1280            # connection — is not news to report to a caller who is merely
1281            # closing. One that died of its own accord is.
1282            failure = None if worker.cancelled() else worker.exception()
1283            if failure is not None:
1284                raise failure
1285        return not running

Stops the consumer and waits, for up to timeout, for the handlers already running.

A message being worked on when this is called is finished and settled, rather than abandoned for the broker to hand to somebody else. A message that had been delivered but not started is given back instead: it is the broker's to hand to another consumer, and holding it here only to work through a retry delay would make closing take as long as the schedule.

A handler still running when the time is up is cancelled, and its message is left unsettled — neither acknowledged nor rejected — so the broker hands it out again once the channel goes. Shutdown is never the reason a message is lost or dead-lettered. The same happens when the caller cancels closing, asyncio.wait_for included, and that cancellation is raised again once the consumer has been cleaned up.

The subscription is released last, after everything has been settled, because a settlement travels on the channel its delivery arrived on.

Parameters
  • timeout: seconds to wait for every running handler together; None waits for as long as they take :returns: True if every handler finished, False if the time ran out first and some were cut off — the consumer is stopped either way
class Connection:
1296class Connection:
1297    """A connection to a broker, and the defaults everything on it inherits.
1298
1299    Built by :func:`connect` in the ordinary case. Taking a transport directly
1300    is for a fake in a test, or for a connection made with settings a URL cannot
1301    carry.
1302
1303    :param transport: how to reach the broker
1304    :param codec: what publishers and consumers use unless they say otherwise
1305    :param origin: what to stamp on published messages, conventionally
1306        ``service@host``
1307    :param retry: what consumers use unless they say otherwise. The default is
1308        one delivery and no second chance, so a handler that calls
1309        ``retry()`` on a connection with no policy dead-letters the message and
1310        says so in the reason. That is deliberate: the alternative default is an
1311        immediate requeue, which is a hot loop against a broker that nobody
1312        asked for
1313    :param prefetch: how many unacknowledged messages a consumer holds
1314    :param max_outstanding_publishes: how many publishes may be waiting for the
1315        broker at once. The ceiling that turns a memory leak into backpressure:
1316        without one, a caller publishing faster than the broker answers
1317        accumulates unconfirmed messages until the process dies, which looks
1318        like throughput right up to the moment it does not. A thousand by
1319        default, which is what Java's ``maxOutstandingPublishes`` and .NET's
1320        ``MaxOutstandingPublishes`` default to
1321    :param confirm_timeout: how long a publish waits for one of those permits,
1322        and then for the broker's confirm, before giving up. Ten seconds by
1323        default, the same as Java's ``confirmTimeout``. Reaching it raises
1324        rather than waiting on, because a publisher stalled for ever behind a
1325        broker that has stopped answering is the failure this bound exists to make visible
1326    :param on_publish: cross-cutting behaviour to wrap every publish on this
1327        connection in, outermost first. See :mod:`acemq_amqp.interceptors`
1328    :param on_consume: the same around every handler.
1329        :meth:`intercept_publish` and :meth:`intercept_consume` add more later
1330    :param observer: where the numbers go. Nothing by default, so a service
1331        that wants none pays for none. See :mod:`acemq_amqp.telemetry`
1332    """
1333
1334    def __init__(
1335        self,
1336        transport: Transport,
1337        *,
1338        codec: Codec | None = None,
1339        origin: str | None = None,
1340        retry: RetryPolicy | None = None,
1341        prefetch: int = DEFAULT_PREFETCH,
1342        max_outstanding_publishes: int = DEFAULT_MAX_OUTSTANDING_PUBLISHES,
1343        confirm_timeout: timedelta = DEFAULT_CONFIRM_TIMEOUT,
1344        on_publish: Sequence[PublishInterceptor] = (),
1345        on_consume: Sequence[ConsumeInterceptor] = (),
1346        observer: Observer | None = None,
1347    ) -> None:
1348        if prefetch < 0:
1349            raise ValueError(f"acemq: prefetch must not be negative, got {prefetch}")
1350        if max_outstanding_publishes < 1:
1351            raise ValueError(
1352                "acemq: max_outstanding_publishes must be at least 1, got "
1353                f"{max_outstanding_publishes}"
1354            )
1355        if confirm_timeout <= timedelta(0):
1356            raise ValueError(
1357                f"acemq: confirm_timeout must be positive, got {confirm_timeout}"
1358            )
1359        self._transport = transport
1360        self._observer: Observer = observer or NullObserver()
1361        self._codec = codec or JsonCodec()
1362        self._origin = origin or default_origin()
1363        self._retry = retry or no_retry()
1364        self._prefetch = prefetch
1365        self._max_outstanding = max_outstanding_publishes
1366        self._confirm_timeout = confirm_timeout
1367        # Built here rather than on first use. An asyncio.Semaphore has bound no
1368        # loop at construction since 3.10, so it is safe to make one outside a
1369        # running loop, and making it here means every publish on this connection
1370        # shares the one counter however many tasks are publishing.
1371        self._outstanding = asyncio.Semaphore(max_outstanding_publishes)
1372        self._in_flight_publishes = 0
1373        self._consumers: list[Consumer] = []
1374        self._publishing: list[PublishInterceptor] = list(on_publish)
1375        self._consuming: list[ConsumeInterceptor] = list(on_consume)
1376        self._closed = False
1377
1378    @property
1379    def transport(self) -> Transport:
1380        """The transport underneath, for anything this library does not wrap."""
1381        return self._transport
1382
1383    @property
1384    def codec(self) -> Codec:
1385        """The codec publishers and consumers use unless told otherwise."""
1386        return self._codec
1387
1388    @property
1389    def origin(self) -> str:
1390        """What published messages are stamped with."""
1391        return self._origin
1392
1393    @property
1394    def retry(self) -> RetryPolicy:
1395        """The retry policy consumers use unless told otherwise."""
1396        return self._retry
1397
1398    @property
1399    def observer(self) -> Observer:
1400        """Where this connection's numbers go."""
1401        return self._observer
1402
1403    @property
1404    def max_outstanding_publishes(self) -> int:
1405        """How many publishes may be waiting for the broker at once."""
1406        return self._max_outstanding
1407
1408    @property
1409    def confirm_timeout(self) -> timedelta:
1410        """How long a publish waits for room before giving up."""
1411        return self._confirm_timeout
1412
1413    @property
1414    def outstanding_publishes(self) -> int:
1415        """How many publishes are waiting for the broker right now.
1416
1417        What a stalled publisher looks like from outside: a number pinned at
1418        :attr:`max_outstanding_publishes` is a broker that has stopped answering,
1419        and it says so before the first :class:`~acemq_amqp.PublishError` does.
1420        """
1421        # Counted here rather than read off the semaphore, which keeps its count
1422        # private. Raised after the permit is taken and lowered before it is
1423        # given back, both inside publish_raw, so it never reads high.
1424        return self._in_flight_publishes
1425
1426    @property
1427    def consumers(self) -> tuple[Consumer, ...]:
1428        """The consumers running on this connection.
1429
1430        A snapshot, and public because a health check that has to say whether
1431        the consumers are alive should not need private access to find them —
1432        the same rule an interceptor follows.
1433        """
1434        return tuple(self._consumers)
1435
1436    @property
1437    def closed(self) -> bool:
1438        """Whether this connection has been closed."""
1439        return self._closed
1440
1441    @property
1442    def blocked(self) -> bool | None:
1443        """Whether the broker has blocked this connection, or ``None`` when the
1444        transport cannot be asked.
1445
1446        RabbitMQ blocks a connection when it is low on memory or disk, and while
1447        it lasts it stops reading that connection's socket: everything sent —
1448        a publish, a declaration, :meth:`health`'s own probe — waits rather than
1449        failing. It is the broker protecting itself and it is not an error, so
1450        it is worth telling apart from the broker having gone away, which looks
1451        identical from outside and wants the opposite response.
1452
1453        ``None`` means the question could not be asked at all, which is a
1454        different fact from ``False`` and is reported as one: a transport that
1455        does not implement
1456        :class:`~acemq_amqp.transport.BlockedState`, or one whose client has
1457        moved the state out of reach. See :attr:`blocked_reason` for why there
1458        may be a boolean and no reason to go with it.
1459        """
1460        transport = self._transport
1461        return transport.blocked if isinstance(transport, BlockedState) else None
1462
1463    @property
1464    def blocked_reason(self) -> str | None:
1465        """What the broker said when it blocked this connection, if anything.
1466
1467        ``None`` when the connection is not blocked, and also ``None`` when the
1468        transport is blocked but cannot say why — which is what the RabbitMQ
1469        transport answers, because aio-pika reads RabbitMQ's reason and does not
1470        keep it. Reporting the block without the reason is the honest half;
1471        inventing a reason would read exactly like one the broker sent.
1472        """
1473        transport = self._transport
1474        return transport.blocked_reason if isinstance(transport, BlockedState) else None
1475
1476    async def health(self, timeout: float = DEFAULT_HEALTH_TIMEOUT) -> HealthReport:
1477        """Whether this connection can reach its broker, and its consumers run.
1478
1479        The broker half is a declaration of a temporary queue, which is the
1480        cheapest thing AMQP offers that actually proves the connection works. A
1481        TCP connection that is open but wedged — the broker paused, the network
1482        black-holing — answers a socket-level check exactly as a healthy one
1483        does, right up until something is asked of it.
1484
1485        The consumer half is the one a probe usually wants and nothing outside
1486        can see. A consumer whose workers have died without it being closed is
1487        one the broker is still sending messages to and nothing is reading, and
1488        from outside that is indistinguishable from a quiet queue.
1489
1490        **A blocked connection is up, with the reason.** The broker blocks a
1491        connection when it is low on disk or memory, and an application that
1492        fails its own readiness check for it is one an orchestrator restarts
1493        into the same blocked broker, having thrown away whatever it was
1494        holding. ``parts["blocked"]`` carries the state either way, and is
1495        ``None`` when the transport could not be asked — see :attr:`blocked`.
1496
1497        **The probe is bounded.** A blocked broker stops reading the socket, so
1498        the round trip this makes is precisely the thing that does not come back
1499        when something is wrong; without a deadline of its own a health check
1500        hangs, and a readiness endpoint that hangs takes the instance out of
1501        rotation with no report at all. A probe that runs out of time is
1502        abandoned rather than waited for, because a request that cannot be
1503        answered cannot reliably be cancelled either.
1504
1505        It costs a round trip, so it is not something to call per request. Wire
1506        it to a readiness probe and let the probe's interval decide how often.
1507
1508        :param timeout: how long to give the broker's answer, three seconds by
1509            default. Shorter than the deadline
1510            :func:`~acemq_amqp.telemetry.aggregate_health` puts around a whole
1511            set of checks, so that this report rather than that one is what an
1512            operator reads when a broker stops answering
1513        :returns: the report. Degraded means working but worth an alert
1514        """
1515        checked = datetime.now(timezone.utc)
1516        consumers = self.consumers
1517        stalled = [consumer.queue for consumer in consumers if not consumer.running]
1518        blocked = self.blocked
1519        parts: dict[str, Any] = {
1520            "consumers": len(consumers),
1521            "in-flight": sum(consumer.in_flight for consumer in consumers),
1522            "blocked": blocked,
1523        }
1524        reason = self.blocked_reason
1525        if reason:
1526            parts["blocked-reason"] = reason
1527
1528        if self._closed:
1529            return HealthReport(
1530                HealthStatus.DOWN, "the connection has been closed", checked, parts
1531            )
1532
1533        if blocked:
1534            # Asked before the probe rather than after it, because the probe is
1535            # what a blocked broker will not answer: a round trip started here
1536            # would spend the whole deadline arriving at the answer this already
1537            # has.
1538            return self._blocked_report(checked, parts, stalled, reason)
1539
1540        # Asking whether a queue nothing has ever declared exists, rather than
1541        # declaring a temporary one. It is the same round trip and it proves the
1542        # same thing, and it creates nothing at all: an exclusive queue is only
1543        # released when the channel that declared it closes, so a probe that
1544        # declared one would leave a queue on the broker for the life of the
1545        # connection and a new one behind every restart.
1546        probe = f"acemq-health-{uuid.uuid4().hex}"
1547        started = time.monotonic()
1548        try:
1549            await self._probe_within(probe, timeout)
1550        except asyncio.TimeoutError:
1551            # A round trip that does not come back is the ordinary way a block
1552            # shows itself, and the notification may have arrived while this was
1553            # waiting. Asked again rather than assumed, because "the broker is
1554            # protecting itself" and "the broker has gone" are the same silence.
1555            blocked = self.blocked
1556            parts["blocked"] = blocked
1557            reason = self.blocked_reason
1558            if reason:
1559                parts["blocked-reason"] = reason
1560            if blocked:
1561                return self._blocked_report(checked, parts, stalled, reason)
1562            return HealthReport(
1563                HealthStatus.DOWN,
1564                f"the broker did not answer within {timeout:g}s",
1565                checked,
1566                parts,
1567            )
1568        except Exception as failure:
1569            parts["error"] = _describe(failure)
1570            return HealthReport(
1571                HealthStatus.DOWN, f"the broker did not answer: {failure}", checked, parts
1572            )
1573        parts["round-trip"] = round(time.monotonic() - started, 4)
1574
1575        if stalled:
1576            # Degraded rather than down: the connection works, and a replacement
1577            # instance would almost certainly stall the same way. Worth waking
1578            # somebody; not worth taking this one out of rotation.
1579            return HealthReport(
1580                HealthStatus.DEGRADED,
1581                _stalled_detail(stalled),
1582                checked,
1583                {**parts, "stalled": sorted(stalled)},
1584            )
1585        return HealthReport(HealthStatus.UP, "", checked, parts)
1586
1587    def _blocked_report(
1588        self,
1589        checked: datetime,
1590        parts: dict[str, Any],
1591        stalled: list[str],
1592        reason: str | None,
1593    ) -> HealthReport:
1594        """What a blocked connection reports: up, with the reason.
1595
1596        Up for the block itself, and still degraded when a consumer of this
1597        process has stopped reading — that is this instance's own failure rather
1598        than the broker's, it outlives the alarm, and a block is not a reason to
1599        stop saying so.
1600        """
1601        detail = self._blocked_detail(reason)
1602        if stalled:
1603            return HealthReport(
1604                HealthStatus.DEGRADED,
1605                f"{_stalled_detail(stalled)}; and {detail}",
1606                checked,
1607                {**parts, "stalled": sorted(stalled)},
1608            )
1609        return HealthReport(HealthStatus.UP, detail, checked, parts)
1610
1611    @staticmethod
1612    def _blocked_detail(reason: str | None) -> str:
1613        """The blocked sentence, with the broker's reason when there is one.
1614
1615        The reason follows a colon, which is how Go and Ruby write it too —
1616        ``blockedPrefix + ": " + reason`` and ``"#{BLOCKED}: #{reason}"``. One
1617        shape across the family means one alert rule reads a blocked broker
1618        whatever language the service happens to be written in.
1619        """
1620        return BLOCKED_DETAIL if not reason else f"{BLOCKED_DETAIL}: {reason}"
1621
1622    async def _probe_within(self, name: str, timeout: float) -> None:
1623        """One round trip to the broker, given ``timeout`` to come back.
1624
1625        The probe runs as a task that is abandoned rather than awaited when the
1626        deadline passes, which is the difference between a bounded check and one
1627        that merely looks bounded: cancelling a request to a broker that has
1628        stopped reading its socket means waiting for a cancellation that travels
1629        the same way the request did.
1630
1631        :raises asyncio.TimeoutError: when the broker did not answer in time
1632        """
1633        probe = asyncio.ensure_future(self._probe(name))
1634        try:
1635            done, _ = await asyncio.wait({probe}, timeout=timeout)
1636        except asyncio.CancelledError:
1637            # The caller gave up on the whole check. Waiting on a task is not
1638            # cancelling it, so it is cancelled here rather than left running
1639            # against a broker nobody is listening to any more.
1640            probe.cancel()
1641            probe.add_done_callback(_retrieved)
1642            raise
1643        if not done:
1644            probe.cancel()
1645            # Whatever it ends as is nobody's news now, and an abandoned task
1646            # whose exception is never retrieved is a warning at collection time
1647            # about a failure that has already been reported as a timeout.
1648            probe.add_done_callback(_retrieved)
1649            raise asyncio.TimeoutError
1650        # Raises what the probe raised, which is what the caller reports.
1651        probe.result()
1652
1653    async def _probe(self, name: str) -> None:
1654        """One round trip to the broker that leaves nothing behind.
1655
1656        A transport that cannot be asked whether a queue exists gets the next
1657        cheapest thing: a temporary queue, removed again straight away. Both
1658        prove the same thing, which is that the connection answers rather than
1659        merely being open.
1660
1661        The temporary queue is classic, and has to be. It is exclusive and
1662        auto-deleting so that it goes when the channel does, and RabbitMQ
1663        refuses a quorum queue that is either — a health check that could not be
1664        declared would report a healthy broker as down.
1665        """
1666        if isinstance(self._transport, QueueAdmin):
1667            await self._transport.queue_exists(name)
1668            return
1669        await self._transport.declare_queue(
1670            name, QueueSpec(durable=False, auto_delete=True, exclusive=True)
1671        )
1672
1673    @property
1674    def publish_interceptors(self) -> tuple[PublishInterceptor, ...]:
1675        """What wraps every publish, outermost first.
1676
1677        A snapshot rather than the list itself, so a publish in progress cannot
1678        be handed a chain that is being edited underneath it.
1679        """
1680        return tuple(self._publishing)
1681
1682    @property
1683    def consume_interceptors(self) -> tuple[ConsumeInterceptor, ...]:
1684        """What wraps every handler, outermost first."""
1685        return tuple(self._consuming)
1686
1687    def intercept_publish(self, interceptor: PublishInterceptor) -> Connection:
1688        """Wraps every publish on this connection in ``interceptor``.
1689
1690        Registered ones run in the order they were added, so this one is
1691        innermost until the next is added. Read at publish time rather than
1692        copied into each publisher, so an interceptor registered during start-up
1693        applies to publishers that already exist — which is what makes it usable
1694        from a framework's wiring rather than only from the line that connects.
1695
1696        Adding at start-up is still what to do. A message already in flight will
1697        not see it, and an interceptor whose whole job is to stamp every message
1698        is not doing it if the first few went without.
1699
1700        :param interceptor: what to wrap the publish in. See
1701            :mod:`acemq_amqp.interceptors`
1702        :returns: this connection, so registrations read as one expression
1703        """
1704        self._publishing.append(interceptor)
1705        return self
1706
1707    def intercept_consume(self, interceptor: ConsumeInterceptor) -> Connection:
1708        """Wraps every handler on this connection in ``interceptor``.
1709
1710        :param interceptor: what to wrap the handler in
1711        :returns: this connection
1712        """
1713        self._consuming.append(interceptor)
1714        return self
1715
1716    async def declare(self, topology: Topology) -> None:
1717        """Applies a topology to this connection's broker.
1718
1719        :param topology: what the broker should have
1720        """
1721        await topology.apply(self._transport)
1722
1723    def publisher(
1724        self,
1725        exchange: str = "",
1726        routing_key: str = "",
1727        *,
1728        codec: Codec | None = None,
1729        persistent: bool = True,
1730        mandatory: bool = True,
1731    ) -> Publisher:
1732        """Builds a publisher for an exchange and routing key.
1733
1734        Publish straight to a queue by leaving the exchange empty: the default
1735        exchange routes to the queue whose name matches the routing key.
1736
1737        :param exchange: where to publish, empty for the default exchange
1738        :param routing_key: what to publish under, or a queue name
1739        :param codec: a codec other than this connection's
1740        :param persistent: ask the broker to write these messages to disk
1741        :param mandatory: fail when a message reaches no queue at all, rather
1742            than letting the broker drop it silently. On by default (AceMQ TCK
1743            requirement AMQP-PUB-006), so a message published to a routing key
1744            nothing is bound to raises :class:`~acemq_amqp.PublishError` with
1745            ``unroutable`` set instead of disappearing. ``mandatory=False`` is the
1746            opt-out, for a fan-out where no subscriber at all is a normal state
1747        :returns: the publisher
1748        """
1749        return Publisher(
1750            self,
1751            exchange,
1752            routing_key,
1753            codec=codec,
1754            persistent=persistent,
1755            mandatory=mandatory,
1756        )
1757
1758    async def consume(
1759        self,
1760        queue: str,
1761        handler: Handler,
1762        *,
1763        codec: Codec | None = None,
1764        retry: RetryPolicy | None = None,
1765        prefetch: int | None = None,
1766        concurrency: int = 1,
1767        tag: str = "",
1768        args: Mapping[str, Any] | None = None,
1769        declare: bool = True,
1770    ) -> Consumer:
1771        """Reads messages from a queue until the returned consumer is closed.
1772
1773        Before it subscribes it declares the queues it will need when a message
1774        fails: ``{queue}.dlq``, ``{queue}.parked``, ``acemq.dlx`` and, when the
1775        retry policy has waits the broker holds, ``acemq.retry`` and the rungs.
1776        See :func:`acemq_amqp.topology.declare_where_failures_go` for exactly
1777        what and why. The source queue is not among them, and neither is
1778        anything a producer needs, so this is not a replacement for declaring a
1779        topology — it is the floor underneath a service that was deployed
1780        without one.
1781
1782        :param queue: what to read
1783        :param handler: what to do with a message; returning an
1784            :class:`~acemq_amqp.Ack` is the decision
1785        :param codec: a codec other than this connection's
1786        :param retry: a policy other than this connection's
1787        :param prefetch: how many unacknowledged messages to hold
1788        :param concurrency: how many messages to work on at once. One by
1789            default, which keeps a queue's messages in order; raising it trades
1790            that order for throughput, which is the right trade for handlers
1791            that spend their time waiting on something else
1792        :param tag: what to call this consumer to the broker
1793        :param args: broker-specific consumer arguments
1794        :param declare: declare the queues above before subscribing. On by
1795            default, because the alternative default loses messages silently.
1796            Turn it off for a login with no ``configure`` permission on the
1797            vhost, which is refused by the broker rather than ignored, and for a
1798            tool draining a queue it does not own — a one-off reader of
1799            ``orders.dlq`` has no business creating ``orders.dlq.dlq``. A
1800            consumer started this way still publishes to those queues, so
1801            somebody else has to have declared them
1802        :returns: the running consumer
1803        """
1804        if self._closed:
1805            raise AceMQError("acemq: this connection is closed")
1806
1807        consumer = Consumer(
1808            self,
1809            queue,
1810            handler,
1811            codec=codec or self._codec,
1812            retry=retry or self._retry,
1813            concurrency=concurrency,
1814            declare=declare,
1815        )
1816        self._consumers.append(consumer)
1817        try:
1818            await consumer._start(
1819                self._prefetch if prefetch is None else prefetch,
1820                tag,
1821                args or {},
1822            )
1823        except BaseException:
1824            self._untrack(consumer)
1825            raise
1826        return consumer
1827
1828    def pipeline(self, name: str) -> PipelineBuilder:
1829        """Starts declaring a pipeline: steps in order, a queue behind each.
1830
1831        The exchange is ``name`` and each step's queue is ``{name}.{step}``, as
1832        in Java, .NET, Go and Ruby. See
1833        :class:`~acemq_amqp.patterns.PipelineBuilder`.
1834
1835        :param name: the pipeline's name, which is also its exchange
1836        :returns: a builder; nothing is declared until its ``build()``
1837        """
1838        from .patterns.routingslip import PipelineBuilder
1839
1840        return PipelineBuilder(self, name)
1841
1842    async def publish_raw(
1843        self, exchange: str, routing_key: str, message: Outbound
1844    ) -> PublishResult:
1845        """Sends bytes that are already encoded, with headers already rendered.
1846
1847        For the retry and dead-letter hops, and for anything else replaying a
1848        message recorded earlier: the payload's class may not exist any more,
1849        and re-encoding it would produce different bytes from the ones that were
1850        committed. Ordinary publishing goes through :class:`Publisher`.
1851
1852        **This is the one place the outstanding-publish bound is taken.** Every
1853        publish in the library comes through here — a :class:`Publisher`, a
1854        retry rung, a dead letter, a replay — so one permit counts them all, and
1855        :meth:`Publisher.send_all` cannot put more messages on the wire at once
1856        than :attr:`max_outstanding_publishes` allows however long the list it
1857        was given is.
1858
1859        :param exchange: where to publish, empty for the default exchange
1860        :param routing_key: what to publish under
1861        :param message: the message, encoded
1862        :returns: what the broker said
1863        :raises PublishingPausedError: when the broker has blocked this
1864            connection. Nothing was sent; retry once it unblocks
1865        :raises PublishError: when every permit is taken and none came free
1866            within :attr:`confirm_timeout`, or when the broker did not confirm
1867            this publish within it. The second may or may not have arrived
1868        """
1869        # Refused rather than queued, before a permit or a byte is spent. A
1870        # blocked broker stops reading the socket, so a publish sent now sits in
1871        # the client's write buffer with no confirm coming until the alarm
1872        # clears, then times out as a failure that may or may not have arrived.
1873        # Go and .NET refuse at the same point for the same reason. ``None``
1874        # means the state could not be read and is not treated as blocked.
1875        if self.blocked is True:
1876            reason = self.blocked_reason
1877            raise PublishingPausedError(
1878                message.message_id,
1879                exchange,
1880                routing_key,
1881                (
1882                    f"{self._blocked_detail(reason)}. Nothing was sent; back off and "
1883                    "retry once the broker unblocks"
1884                ),
1885            )
1886
1887        # Taken before the message is written and not after, which is the whole
1888        # point: a bound applied afterwards has already let the message into
1889        # memory. The permit is given back in the ``finally`` below on every
1890        # path there is — the publish returning, the publish raising, and this
1891        # task being cancelled while the broker is still thinking — because a
1892        # permit lost on any one of those is a connection that publishes a
1893        # thousand more messages and then stops for ever.
1894        try:
1895            await asyncio.wait_for(
1896                self._outstanding.acquire(), self._confirm_timeout.total_seconds()
1897            )
1898        except asyncio.TimeoutError as stalled:
1899            # Said rather than waited out. A publisher parked behind a broker
1900            # that has stopped answering is indistinguishable from a quiet
1901            # service, and this sentence is the one Java raises word for word so
1902            # that an operator reading a log has one thing to recognise.
1903            raise PublishError(
1904                message.message_id,
1905                exchange,
1906                routing_key,
1907                (
1908                    f"{self._max_outstanding} publishes are already waiting for a "
1909                    f"confirm and none completed within {self._confirm_timeout}. "
1910                    "The broker is not keeping up; publish more slowly rather than "
1911                    "buffering more."
1912                ),
1913            ) from stalled
1914
1915        self._in_flight_publishes += 1
1916        try:
1917            # Bounded as well, by the same timeout. RabbitMQ says a connection is
1918            # blocked only once it publishes, so the first publish after an alarm
1919            # is written and then held with no confirm until the alarm clears --
1920            # minutes, or never. Said here as a failure, not a refusal: it was
1921            # written, so it may have arrived. The publish after it sees the
1922            # block and is refused above. .NET bounds the same wait the same way.
1923            result = await asyncio.wait_for(
1924                self._transport.publish(exchange, routing_key, message),
1925                self._confirm_timeout.total_seconds(),
1926            )
1927        except asyncio.TimeoutError as unconfirmed:
1928            raise PublishError(
1929                message.message_id,
1930                exchange,
1931                routing_key,
1932                (
1933                    f"the broker did not confirm this publish within "
1934                    f"{self._confirm_timeout}. It may or may not have been stored, "
1935                    "so treat it as neither sent nor lost"
1936                ),
1937            ) from unconfirmed
1938        finally:
1939            self._in_flight_publishes -= 1
1940            self._outstanding.release()
1941
1942        # A nack is the broker declining to keep a message it was asked to take, and
1943        # it is raised here rather than returned.
1944        #
1945        # It used to be returned, and `confirmed` was read nowhere in this library
1946        # except a telemetry label -- so a caller who did not inspect the result
1947        # carried on believing the message had gone somewhere, and Java, .NET, Go and
1948        # Ruby all raised on the same event. Worse than the wrong belief: the outbox
1949        # relay removes a record because the publish did not raise, so a nack deleted
1950        # a record for a message the broker had refused. At-most-once, in the pattern
1951        # whose whole purpose is not losing anything.
1952        #
1953        # Checked here because this is the one place every publish in the library
1954        # comes through -- a Publisher, a retry rung, a dead letter, a replay, the
1955        # outbox -- so one check covers all of them, and anything that settles or
1956        # deletes on the strength of a publish returning now hears the refusal.
1957        #
1958        # Distinct from unroutable, which the Publisher path reports separately and
1959        # which sets `unroutable`: the broker could route this one and would not keep
1960        # it, and the two want different responses.
1961        #
1962        # So a returned message is passed back rather than raised here. The
1963        # RabbitMQ transport reports a Basic.Return as not confirmed as well as
1964        # not routed, and raising it as a nack hid ``routed`` from every caller
1965        # that reads it: a mandatory Publisher said "refused" rather than
1966        # "reached no queue", and the retry and dead-letter hops never reached
1967        # the fallbacks written for a queue that is not there.
1968        if not result.confirmed and result.routed:
1969            raise PublishError(
1970                message.message_id,
1971                exchange,
1972                routing_key,
1973                (
1974                    "the broker refused to confirm it. The message reached the broker "
1975                    "and the broker has not taken responsibility for it, so it must be "
1976                    "treated as not sent"
1977                ),
1978            )
1979
1980        return result
1981
1982    async def pull(self, queue: str) -> Delivery | None:
1983        """Takes one message off a queue, or ``None`` when there is none waiting.
1984
1985        For tools rather than for services: it is a round trip per message where
1986        :meth:`consume` gets a stream. What it can do that a consumer cannot is
1987        say that a queue is empty, which is what anything working through a
1988        backlog and then stopping — a replay, a drain — has to know.
1989
1990        The delivery comes back unsettled, so the caller decides whether it is
1991        gone or goes back.
1992
1993        :param queue: what to read from
1994        :returns: the delivery, or ``None``
1995        """
1996        return await self._source().pull(queue)
1997
1998    async def queue_exists(self, queue: str) -> bool:
1999        """Whether a queue is on the broker, creating nothing."""
2000        return await self._admin().queue_exists(queue)
2001
2002    async def message_count(self, queue: str) -> int:
2003        """How many messages are waiting on a queue."""
2004        return await self._admin().message_count(queue)
2005
2006    async def delete_queue(self, queue: str) -> None:
2007        """Removes a queue and every message still on it."""
2008        await self._admin().delete_queue(queue)
2009
2010    def _admin(self) -> QueueAdmin:
2011        if not isinstance(self._transport, QueueAdmin):
2012            raise AceMQError(
2013                f"acemq: the {type(self._transport).__name__} transport cannot manage queues"
2014            )
2015        return self._transport
2016
2017    def _source(self) -> MessageSource:
2018        if not isinstance(self._transport, MessageSource):
2019            raise AceMQError(
2020                f"acemq: the {type(self._transport).__name__} transport cannot be "
2021                "asked for one message at a time"
2022            )
2023        return self._transport
2024
2025    def _untrack(self, consumer: Consumer) -> None:
2026        if consumer in self._consumers:
2027            self._consumers.remove(consumer)
2028
2029    async def close(self, *, timeout: float | None = DEFAULT_DRAIN_TIMEOUT) -> bool:
2030        """Stops every consumer on this connection and releases it.
2031
2032        Consumers first, and their handlers given up to ``timeout`` to finish,
2033        so a message being worked on when this is called is settled rather than
2034        returned to the queue for somebody else to redo. The bound is one
2035        deadline for every handler of every consumer, not one each: they are
2036        all drained at once. A handler still running at the deadline is
2037        cancelled and its message left unsettled, for the broker to redeliver —
2038        see :meth:`Consumer.close`.
2039
2040        The connection is released whatever happens, including when the caller
2041        cancels closing; that cancellation is raised again afterwards.
2042
2043        :param timeout: seconds to wait for the running handlers; ``None``
2044            waits for as long as they take
2045        :returns: ``True`` if every handler finished, ``False`` if the time ran
2046            out first
2047        """
2048        if self._closed:
2049            return True
2050        self._closed = True
2051        try:
2052            drained = await asyncio.gather(
2053                *(consumer.close(timeout=timeout) for consumer in list(self._consumers)),
2054                return_exceptions=True,
2055            )
2056        finally:
2057            await self._transport.close()
2058        for outcome in drained:
2059            if isinstance(outcome, BaseException):
2060                raise outcome
2061        return all(drained)
2062
2063    async def __aenter__(self) -> Connection:
2064        return self
2065
2066    async def __aexit__(self, *_: object) -> None:
2067        await self.close()

A connection to a broker, and the defaults everything on it inherits.

Built by connect() in the ordinary case. Taking a transport directly is for a fake in a test, or for a connection made with settings a URL cannot carry.

Parameters
  • transport: how to reach the broker
  • codec: what publishers and consumers use unless they say otherwise
  • origin: what to stamp on published messages, conventionally service@host
  • retry: what consumers use unless they say otherwise. The default is one delivery and no second chance, so a handler that calls retry() on a connection with no policy dead-letters the message and says so in the reason. That is deliberate: the alternative default is an immediate requeue, which is a hot loop against a broker that nobody asked for
  • prefetch: how many unacknowledged messages a consumer holds
  • max_outstanding_publishes: how many publishes may be waiting for the broker at once. The ceiling that turns a memory leak into backpressure: without one, a caller publishing faster than the broker answers accumulates unconfirmed messages until the process dies, which looks like throughput right up to the moment it does not. A thousand by default, which is what Java's maxOutstandingPublishes and .NET's MaxOutstandingPublishes default to
  • confirm_timeout: how long a publish waits for one of those permits, and then for the broker's confirm, before giving up. Ten seconds by default, the same as Java's confirmTimeout. Reaching it raises rather than waiting on, because a publisher stalled for ever behind a broker that has stopped answering is the failure this bound exists to make visible
  • on_publish: cross-cutting behaviour to wrap every publish on this connection in, outermost first. See acemq_amqp.interceptors
  • on_consume: the same around every handler. intercept_publish() and intercept_consume() add more later
  • observer: where the numbers go. Nothing by default, so a service that wants none pays for none. See acemq_amqp.telemetry
Connection( transport: acemq_amqp.Transport, *, codec: acemq_amqp.Codec | None = None, origin: str | None = None, retry: acemq_amqp.RetryPolicy | None = None, prefetch: int = 20, max_outstanding_publishes: int = 1000, confirm_timeout: datetime.timedelta = datetime.timedelta(seconds=10), on_publish: Sequence[Callable[[acemq_amqp.PublishContext, Callable[[acemq_amqp.PublishContext], Awaitable[acemq_amqp.PublishResult]]], Awaitable[acemq_amqp.PublishResult]]] = (), on_consume: Sequence[Callable[[acemq_amqp.ConsumeContext, Callable[[acemq_amqp.ConsumeContext], Awaitable[acemq_amqp.Ack]]], Awaitable[acemq_amqp.Ack]]] = (), observer: acemq_amqp.Observer | None = None)
1334    def __init__(
1335        self,
1336        transport: Transport,
1337        *,
1338        codec: Codec | None = None,
1339        origin: str | None = None,
1340        retry: RetryPolicy | None = None,
1341        prefetch: int = DEFAULT_PREFETCH,
1342        max_outstanding_publishes: int = DEFAULT_MAX_OUTSTANDING_PUBLISHES,
1343        confirm_timeout: timedelta = DEFAULT_CONFIRM_TIMEOUT,
1344        on_publish: Sequence[PublishInterceptor] = (),
1345        on_consume: Sequence[ConsumeInterceptor] = (),
1346        observer: Observer | None = None,
1347    ) -> None:
1348        if prefetch < 0:
1349            raise ValueError(f"acemq: prefetch must not be negative, got {prefetch}")
1350        if max_outstanding_publishes < 1:
1351            raise ValueError(
1352                "acemq: max_outstanding_publishes must be at least 1, got "
1353                f"{max_outstanding_publishes}"
1354            )
1355        if confirm_timeout <= timedelta(0):
1356            raise ValueError(
1357                f"acemq: confirm_timeout must be positive, got {confirm_timeout}"
1358            )
1359        self._transport = transport
1360        self._observer: Observer = observer or NullObserver()
1361        self._codec = codec or JsonCodec()
1362        self._origin = origin or default_origin()
1363        self._retry = retry or no_retry()
1364        self._prefetch = prefetch
1365        self._max_outstanding = max_outstanding_publishes
1366        self._confirm_timeout = confirm_timeout
1367        # Built here rather than on first use. An asyncio.Semaphore has bound no
1368        # loop at construction since 3.10, so it is safe to make one outside a
1369        # running loop, and making it here means every publish on this connection
1370        # shares the one counter however many tasks are publishing.
1371        self._outstanding = asyncio.Semaphore(max_outstanding_publishes)
1372        self._in_flight_publishes = 0
1373        self._consumers: list[Consumer] = []
1374        self._publishing: list[PublishInterceptor] = list(on_publish)
1375        self._consuming: list[ConsumeInterceptor] = list(on_consume)
1376        self._closed = False
transport: acemq_amqp.Transport
1378    @property
1379    def transport(self) -> Transport:
1380        """The transport underneath, for anything this library does not wrap."""
1381        return self._transport

The transport underneath, for anything this library does not wrap.

codec: acemq_amqp.Codec
1383    @property
1384    def codec(self) -> Codec:
1385        """The codec publishers and consumers use unless told otherwise."""
1386        return self._codec

The codec publishers and consumers use unless told otherwise.

origin: str
1388    @property
1389    def origin(self) -> str:
1390        """What published messages are stamped with."""
1391        return self._origin

What published messages are stamped with.

retry: acemq_amqp.RetryPolicy
1393    @property
1394    def retry(self) -> RetryPolicy:
1395        """The retry policy consumers use unless told otherwise."""
1396        return self._retry

The retry policy consumers use unless told otherwise.

observer: acemq_amqp.Observer
1398    @property
1399    def observer(self) -> Observer:
1400        """Where this connection's numbers go."""
1401        return self._observer

Where this connection's numbers go.

max_outstanding_publishes: int
1403    @property
1404    def max_outstanding_publishes(self) -> int:
1405        """How many publishes may be waiting for the broker at once."""
1406        return self._max_outstanding

How many publishes may be waiting for the broker at once.

confirm_timeout: datetime.timedelta
1408    @property
1409    def confirm_timeout(self) -> timedelta:
1410        """How long a publish waits for room before giving up."""
1411        return self._confirm_timeout

How long a publish waits for room before giving up.

outstanding_publishes: int
1413    @property
1414    def outstanding_publishes(self) -> int:
1415        """How many publishes are waiting for the broker right now.
1416
1417        What a stalled publisher looks like from outside: a number pinned at
1418        :attr:`max_outstanding_publishes` is a broker that has stopped answering,
1419        and it says so before the first :class:`~acemq_amqp.PublishError` does.
1420        """
1421        # Counted here rather than read off the semaphore, which keeps its count
1422        # private. Raised after the permit is taken and lowered before it is
1423        # given back, both inside publish_raw, so it never reads high.
1424        return self._in_flight_publishes

How many publishes are waiting for the broker right now.

What a stalled publisher looks like from outside: a number pinned at max_outstanding_publishes is a broker that has stopped answering, and it says so before the first ~acemq_amqp.PublishError does.

consumers: tuple[Consumer, ...]
1426    @property
1427    def consumers(self) -> tuple[Consumer, ...]:
1428        """The consumers running on this connection.
1429
1430        A snapshot, and public because a health check that has to say whether
1431        the consumers are alive should not need private access to find them —
1432        the same rule an interceptor follows.
1433        """
1434        return tuple(self._consumers)

The consumers running on this connection.

A snapshot, and public because a health check that has to say whether the consumers are alive should not need private access to find them — the same rule an interceptor follows.

closed: bool
1436    @property
1437    def closed(self) -> bool:
1438        """Whether this connection has been closed."""
1439        return self._closed

Whether this connection has been closed.

blocked: bool | None
1441    @property
1442    def blocked(self) -> bool | None:
1443        """Whether the broker has blocked this connection, or ``None`` when the
1444        transport cannot be asked.
1445
1446        RabbitMQ blocks a connection when it is low on memory or disk, and while
1447        it lasts it stops reading that connection's socket: everything sent —
1448        a publish, a declaration, :meth:`health`'s own probe — waits rather than
1449        failing. It is the broker protecting itself and it is not an error, so
1450        it is worth telling apart from the broker having gone away, which looks
1451        identical from outside and wants the opposite response.
1452
1453        ``None`` means the question could not be asked at all, which is a
1454        different fact from ``False`` and is reported as one: a transport that
1455        does not implement
1456        :class:`~acemq_amqp.transport.BlockedState`, or one whose client has
1457        moved the state out of reach. See :attr:`blocked_reason` for why there
1458        may be a boolean and no reason to go with it.
1459        """
1460        transport = self._transport
1461        return transport.blocked if isinstance(transport, BlockedState) else None

Whether the broker has blocked this connection, or None when the transport cannot be asked.

RabbitMQ blocks a connection when it is low on memory or disk, and while it lasts it stops reading that connection's socket: everything sent — a publish, a declaration, health()'s own probe — waits rather than failing. It is the broker protecting itself and it is not an error, so it is worth telling apart from the broker having gone away, which looks identical from outside and wants the opposite response.

None means the question could not be asked at all, which is a different fact from False and is reported as one: a transport that does not implement ~acemq_amqp.transport.BlockedState, or one whose client has moved the state out of reach. See blocked_reason for why there may be a boolean and no reason to go with it.

blocked_reason: str | None
1463    @property
1464    def blocked_reason(self) -> str | None:
1465        """What the broker said when it blocked this connection, if anything.
1466
1467        ``None`` when the connection is not blocked, and also ``None`` when the
1468        transport is blocked but cannot say why — which is what the RabbitMQ
1469        transport answers, because aio-pika reads RabbitMQ's reason and does not
1470        keep it. Reporting the block without the reason is the honest half;
1471        inventing a reason would read exactly like one the broker sent.
1472        """
1473        transport = self._transport
1474        return transport.blocked_reason if isinstance(transport, BlockedState) else None

What the broker said when it blocked this connection, if anything.

None when the connection is not blocked, and also None when the transport is blocked but cannot say why — which is what the RabbitMQ transport answers, because aio-pika reads RabbitMQ's reason and does not keep it. Reporting the block without the reason is the honest half; inventing a reason would read exactly like one the broker sent.

async def health(self, timeout: float = 3.0) -> acemq_amqp.HealthReport:
1476    async def health(self, timeout: float = DEFAULT_HEALTH_TIMEOUT) -> HealthReport:
1477        """Whether this connection can reach its broker, and its consumers run.
1478
1479        The broker half is a declaration of a temporary queue, which is the
1480        cheapest thing AMQP offers that actually proves the connection works. A
1481        TCP connection that is open but wedged — the broker paused, the network
1482        black-holing — answers a socket-level check exactly as a healthy one
1483        does, right up until something is asked of it.
1484
1485        The consumer half is the one a probe usually wants and nothing outside
1486        can see. A consumer whose workers have died without it being closed is
1487        one the broker is still sending messages to and nothing is reading, and
1488        from outside that is indistinguishable from a quiet queue.
1489
1490        **A blocked connection is up, with the reason.** The broker blocks a
1491        connection when it is low on disk or memory, and an application that
1492        fails its own readiness check for it is one an orchestrator restarts
1493        into the same blocked broker, having thrown away whatever it was
1494        holding. ``parts["blocked"]`` carries the state either way, and is
1495        ``None`` when the transport could not be asked — see :attr:`blocked`.
1496
1497        **The probe is bounded.** A blocked broker stops reading the socket, so
1498        the round trip this makes is precisely the thing that does not come back
1499        when something is wrong; without a deadline of its own a health check
1500        hangs, and a readiness endpoint that hangs takes the instance out of
1501        rotation with no report at all. A probe that runs out of time is
1502        abandoned rather than waited for, because a request that cannot be
1503        answered cannot reliably be cancelled either.
1504
1505        It costs a round trip, so it is not something to call per request. Wire
1506        it to a readiness probe and let the probe's interval decide how often.
1507
1508        :param timeout: how long to give the broker's answer, three seconds by
1509            default. Shorter than the deadline
1510            :func:`~acemq_amqp.telemetry.aggregate_health` puts around a whole
1511            set of checks, so that this report rather than that one is what an
1512            operator reads when a broker stops answering
1513        :returns: the report. Degraded means working but worth an alert
1514        """
1515        checked = datetime.now(timezone.utc)
1516        consumers = self.consumers
1517        stalled = [consumer.queue for consumer in consumers if not consumer.running]
1518        blocked = self.blocked
1519        parts: dict[str, Any] = {
1520            "consumers": len(consumers),
1521            "in-flight": sum(consumer.in_flight for consumer in consumers),
1522            "blocked": blocked,
1523        }
1524        reason = self.blocked_reason
1525        if reason:
1526            parts["blocked-reason"] = reason
1527
1528        if self._closed:
1529            return HealthReport(
1530                HealthStatus.DOWN, "the connection has been closed", checked, parts
1531            )
1532
1533        if blocked:
1534            # Asked before the probe rather than after it, because the probe is
1535            # what a blocked broker will not answer: a round trip started here
1536            # would spend the whole deadline arriving at the answer this already
1537            # has.
1538            return self._blocked_report(checked, parts, stalled, reason)
1539
1540        # Asking whether a queue nothing has ever declared exists, rather than
1541        # declaring a temporary one. It is the same round trip and it proves the
1542        # same thing, and it creates nothing at all: an exclusive queue is only
1543        # released when the channel that declared it closes, so a probe that
1544        # declared one would leave a queue on the broker for the life of the
1545        # connection and a new one behind every restart.
1546        probe = f"acemq-health-{uuid.uuid4().hex}"
1547        started = time.monotonic()
1548        try:
1549            await self._probe_within(probe, timeout)
1550        except asyncio.TimeoutError:
1551            # A round trip that does not come back is the ordinary way a block
1552            # shows itself, and the notification may have arrived while this was
1553            # waiting. Asked again rather than assumed, because "the broker is
1554            # protecting itself" and "the broker has gone" are the same silence.
1555            blocked = self.blocked
1556            parts["blocked"] = blocked
1557            reason = self.blocked_reason
1558            if reason:
1559                parts["blocked-reason"] = reason
1560            if blocked:
1561                return self._blocked_report(checked, parts, stalled, reason)
1562            return HealthReport(
1563                HealthStatus.DOWN,
1564                f"the broker did not answer within {timeout:g}s",
1565                checked,
1566                parts,
1567            )
1568        except Exception as failure:
1569            parts["error"] = _describe(failure)
1570            return HealthReport(
1571                HealthStatus.DOWN, f"the broker did not answer: {failure}", checked, parts
1572            )
1573        parts["round-trip"] = round(time.monotonic() - started, 4)
1574
1575        if stalled:
1576            # Degraded rather than down: the connection works, and a replacement
1577            # instance would almost certainly stall the same way. Worth waking
1578            # somebody; not worth taking this one out of rotation.
1579            return HealthReport(
1580                HealthStatus.DEGRADED,
1581                _stalled_detail(stalled),
1582                checked,
1583                {**parts, "stalled": sorted(stalled)},
1584            )
1585        return HealthReport(HealthStatus.UP, "", checked, parts)

Whether this connection can reach its broker, and its consumers run.

The broker half is a declaration of a temporary queue, which is the cheapest thing AMQP offers that actually proves the connection works. A TCP connection that is open but wedged — the broker paused, the network black-holing — answers a socket-level check exactly as a healthy one does, right up until something is asked of it.

The consumer half is the one a probe usually wants and nothing outside can see. A consumer whose workers have died without it being closed is one the broker is still sending messages to and nothing is reading, and from outside that is indistinguishable from a quiet queue.

A blocked connection is up, with the reason. The broker blocks a connection when it is low on disk or memory, and an application that fails its own readiness check for it is one an orchestrator restarts into the same blocked broker, having thrown away whatever it was holding. parts["blocked"] carries the state either way, and is None when the transport could not be asked — see blocked.

The probe is bounded. A blocked broker stops reading the socket, so the round trip this makes is precisely the thing that does not come back when something is wrong; without a deadline of its own a health check hangs, and a readiness endpoint that hangs takes the instance out of rotation with no report at all. A probe that runs out of time is abandoned rather than waited for, because a request that cannot be answered cannot reliably be cancelled either.

It costs a round trip, so it is not something to call per request. Wire it to a readiness probe and let the probe's interval decide how often.

Parameters
  • timeout: how long to give the broker's answer, three seconds by default. Shorter than the deadline ~acemq_amqp.telemetry.aggregate_health() puts around a whole set of checks, so that this report rather than that one is what an operator reads when a broker stops answering :returns: the report. Degraded means working but worth an alert
publish_interceptors: tuple[Callable[[acemq_amqp.PublishContext, Callable[[acemq_amqp.PublishContext], Awaitable[acemq_amqp.PublishResult]]], Awaitable[acemq_amqp.PublishResult]], ...]
1673    @property
1674    def publish_interceptors(self) -> tuple[PublishInterceptor, ...]:
1675        """What wraps every publish, outermost first.
1676
1677        A snapshot rather than the list itself, so a publish in progress cannot
1678        be handed a chain that is being edited underneath it.
1679        """
1680        return tuple(self._publishing)

What wraps every publish, outermost first.

A snapshot rather than the list itself, so a publish in progress cannot be handed a chain that is being edited underneath it.

consume_interceptors: tuple[Callable[[acemq_amqp.ConsumeContext, Callable[[acemq_amqp.ConsumeContext], Awaitable[acemq_amqp.Ack]]], Awaitable[acemq_amqp.Ack]], ...]
1682    @property
1683    def consume_interceptors(self) -> tuple[ConsumeInterceptor, ...]:
1684        """What wraps every handler, outermost first."""
1685        return tuple(self._consuming)

What wraps every handler, outermost first.

def intercept_publish( self, interceptor: Callable[[acemq_amqp.PublishContext, Callable[[acemq_amqp.PublishContext], Awaitable[acemq_amqp.PublishResult]]], Awaitable[acemq_amqp.PublishResult]]) -> Connection:
1687    def intercept_publish(self, interceptor: PublishInterceptor) -> Connection:
1688        """Wraps every publish on this connection in ``interceptor``.
1689
1690        Registered ones run in the order they were added, so this one is
1691        innermost until the next is added. Read at publish time rather than
1692        copied into each publisher, so an interceptor registered during start-up
1693        applies to publishers that already exist — which is what makes it usable
1694        from a framework's wiring rather than only from the line that connects.
1695
1696        Adding at start-up is still what to do. A message already in flight will
1697        not see it, and an interceptor whose whole job is to stamp every message
1698        is not doing it if the first few went without.
1699
1700        :param interceptor: what to wrap the publish in. See
1701            :mod:`acemq_amqp.interceptors`
1702        :returns: this connection, so registrations read as one expression
1703        """
1704        self._publishing.append(interceptor)
1705        return self

Wraps every publish on this connection in interceptor.

Registered ones run in the order they were added, so this one is innermost until the next is added. Read at publish time rather than copied into each publisher, so an interceptor registered during start-up applies to publishers that already exist — which is what makes it usable from a framework's wiring rather than only from the line that connects.

Adding at start-up is still what to do. A message already in flight will not see it, and an interceptor whose whole job is to stamp every message is not doing it if the first few went without.

Parameters
  • interceptor: what to wrap the publish in. See acemq_amqp.interceptors :returns: this connection, so registrations read as one expression
def intercept_consume( self, interceptor: Callable[[acemq_amqp.ConsumeContext, Callable[[acemq_amqp.ConsumeContext], Awaitable[acemq_amqp.Ack]]], Awaitable[acemq_amqp.Ack]]) -> Connection:
1707    def intercept_consume(self, interceptor: ConsumeInterceptor) -> Connection:
1708        """Wraps every handler on this connection in ``interceptor``.
1709
1710        :param interceptor: what to wrap the handler in
1711        :returns: this connection
1712        """
1713        self._consuming.append(interceptor)
1714        return self

Wraps every handler on this connection in interceptor.

Parameters
  • interceptor: what to wrap the handler in :returns: this connection
async def declare(self, topology: acemq_amqp.Topology) -> None:
1716    async def declare(self, topology: Topology) -> None:
1717        """Applies a topology to this connection's broker.
1718
1719        :param topology: what the broker should have
1720        """
1721        await topology.apply(self._transport)

Applies a topology to this connection's broker.

Parameters
  • topology: what the broker should have
def publisher( self, exchange: str = '', routing_key: str = '', *, codec: acemq_amqp.Codec | None = None, persistent: bool = True, mandatory: bool = True) -> Publisher:
1723    def publisher(
1724        self,
1725        exchange: str = "",
1726        routing_key: str = "",
1727        *,
1728        codec: Codec | None = None,
1729        persistent: bool = True,
1730        mandatory: bool = True,
1731    ) -> Publisher:
1732        """Builds a publisher for an exchange and routing key.
1733
1734        Publish straight to a queue by leaving the exchange empty: the default
1735        exchange routes to the queue whose name matches the routing key.
1736
1737        :param exchange: where to publish, empty for the default exchange
1738        :param routing_key: what to publish under, or a queue name
1739        :param codec: a codec other than this connection's
1740        :param persistent: ask the broker to write these messages to disk
1741        :param mandatory: fail when a message reaches no queue at all, rather
1742            than letting the broker drop it silently. On by default (AceMQ TCK
1743            requirement AMQP-PUB-006), so a message published to a routing key
1744            nothing is bound to raises :class:`~acemq_amqp.PublishError` with
1745            ``unroutable`` set instead of disappearing. ``mandatory=False`` is the
1746            opt-out, for a fan-out where no subscriber at all is a normal state
1747        :returns: the publisher
1748        """
1749        return Publisher(
1750            self,
1751            exchange,
1752            routing_key,
1753            codec=codec,
1754            persistent=persistent,
1755            mandatory=mandatory,
1756        )

Builds a publisher for an exchange and routing key.

Publish straight to a queue by leaving the exchange empty: the default exchange routes to the queue whose name matches the routing key.

Parameters
  • exchange: where to publish, empty for the default exchange
  • routing_key: what to publish under, or a queue name
  • codec: a codec other than this connection's
  • persistent: ask the broker to write these messages to disk
  • mandatory: fail when a message reaches no queue at all, rather than letting the broker drop it silently. On by default (AceMQ TCK requirement AMQP-PUB-006), so a message published to a routing key nothing is bound to raises ~acemq_amqp.PublishError with unroutable set instead of disappearing. mandatory=False is the opt-out, for a fan-out where no subscriber at all is a normal state :returns: the publisher
async def consume( self, queue: str, handler: Callable[Message, acemq_amqp.Ack | Awaitable[acemq_amqp.Ack]], *, codec: acemq_amqp.Codec | None = None, retry: acemq_amqp.RetryPolicy | None = None, prefetch: int | None = None, concurrency: int = 1, tag: str = '', args: Mapping[str, typing.Any] | None = None, declare: bool = True) -> Consumer:
1758    async def consume(
1759        self,
1760        queue: str,
1761        handler: Handler,
1762        *,
1763        codec: Codec | None = None,
1764        retry: RetryPolicy | None = None,
1765        prefetch: int | None = None,
1766        concurrency: int = 1,
1767        tag: str = "",
1768        args: Mapping[str, Any] | None = None,
1769        declare: bool = True,
1770    ) -> Consumer:
1771        """Reads messages from a queue until the returned consumer is closed.
1772
1773        Before it subscribes it declares the queues it will need when a message
1774        fails: ``{queue}.dlq``, ``{queue}.parked``, ``acemq.dlx`` and, when the
1775        retry policy has waits the broker holds, ``acemq.retry`` and the rungs.
1776        See :func:`acemq_amqp.topology.declare_where_failures_go` for exactly
1777        what and why. The source queue is not among them, and neither is
1778        anything a producer needs, so this is not a replacement for declaring a
1779        topology — it is the floor underneath a service that was deployed
1780        without one.
1781
1782        :param queue: what to read
1783        :param handler: what to do with a message; returning an
1784            :class:`~acemq_amqp.Ack` is the decision
1785        :param codec: a codec other than this connection's
1786        :param retry: a policy other than this connection's
1787        :param prefetch: how many unacknowledged messages to hold
1788        :param concurrency: how many messages to work on at once. One by
1789            default, which keeps a queue's messages in order; raising it trades
1790            that order for throughput, which is the right trade for handlers
1791            that spend their time waiting on something else
1792        :param tag: what to call this consumer to the broker
1793        :param args: broker-specific consumer arguments
1794        :param declare: declare the queues above before subscribing. On by
1795            default, because the alternative default loses messages silently.
1796            Turn it off for a login with no ``configure`` permission on the
1797            vhost, which is refused by the broker rather than ignored, and for a
1798            tool draining a queue it does not own — a one-off reader of
1799            ``orders.dlq`` has no business creating ``orders.dlq.dlq``. A
1800            consumer started this way still publishes to those queues, so
1801            somebody else has to have declared them
1802        :returns: the running consumer
1803        """
1804        if self._closed:
1805            raise AceMQError("acemq: this connection is closed")
1806
1807        consumer = Consumer(
1808            self,
1809            queue,
1810            handler,
1811            codec=codec or self._codec,
1812            retry=retry or self._retry,
1813            concurrency=concurrency,
1814            declare=declare,
1815        )
1816        self._consumers.append(consumer)
1817        try:
1818            await consumer._start(
1819                self._prefetch if prefetch is None else prefetch,
1820                tag,
1821                args or {},
1822            )
1823        except BaseException:
1824            self._untrack(consumer)
1825            raise
1826        return consumer

Reads messages from a queue until the returned consumer is closed.

Before it subscribes it declares the queues it will need when a message fails: {queue}.dlq, {queue}.parked, acemq.dlx and, when the retry policy has waits the broker holds, acemq.retry and the rungs. See acemq_amqp.topology.declare_where_failures_go() for exactly what and why. The source queue is not among them, and neither is anything a producer needs, so this is not a replacement for declaring a topology — it is the floor underneath a service that was deployed without one.

Parameters
  • queue: what to read
  • handler: what to do with a message; returning an ~acemq_amqp.Ack is the decision
  • codec: a codec other than this connection's
  • retry: a policy other than this connection's
  • prefetch: how many unacknowledged messages to hold
  • concurrency: how many messages to work on at once. One by default, which keeps a queue's messages in order; raising it trades that order for throughput, which is the right trade for handlers that spend their time waiting on something else
  • tag: what to call this consumer to the broker
  • args: broker-specific consumer arguments
  • declare: declare the queues above before subscribing. On by default, because the alternative default loses messages silently. Turn it off for a login with no configure permission on the vhost, which is refused by the broker rather than ignored, and for a tool draining a queue it does not own — a one-off reader of orders.dlq has no business creating orders.dlq.dlq. A consumer started this way still publishes to those queues, so somebody else has to have declared them :returns: the running consumer
def pipeline(self, name: str) -> acemq_amqp.patterns.PipelineBuilder:
1828    def pipeline(self, name: str) -> PipelineBuilder:
1829        """Starts declaring a pipeline: steps in order, a queue behind each.
1830
1831        The exchange is ``name`` and each step's queue is ``{name}.{step}``, as
1832        in Java, .NET, Go and Ruby. See
1833        :class:`~acemq_amqp.patterns.PipelineBuilder`.
1834
1835        :param name: the pipeline's name, which is also its exchange
1836        :returns: a builder; nothing is declared until its ``build()``
1837        """
1838        from .patterns.routingslip import PipelineBuilder
1839
1840        return PipelineBuilder(self, name)

Starts declaring a pipeline: steps in order, a queue behind each.

The exchange is name and each step's queue is {name}.{step}, as in Java, .NET, Go and Ruby. See ~acemq_amqp.patterns.PipelineBuilder.

Parameters
  • name: the pipeline's name, which is also its exchange :returns: a builder; nothing is declared until its build()
async def publish_raw( self, exchange: str, routing_key: str, message: acemq_amqp.Outbound) -> acemq_amqp.PublishResult:
1842    async def publish_raw(
1843        self, exchange: str, routing_key: str, message: Outbound
1844    ) -> PublishResult:
1845        """Sends bytes that are already encoded, with headers already rendered.
1846
1847        For the retry and dead-letter hops, and for anything else replaying a
1848        message recorded earlier: the payload's class may not exist any more,
1849        and re-encoding it would produce different bytes from the ones that were
1850        committed. Ordinary publishing goes through :class:`Publisher`.
1851
1852        **This is the one place the outstanding-publish bound is taken.** Every
1853        publish in the library comes through here — a :class:`Publisher`, a
1854        retry rung, a dead letter, a replay — so one permit counts them all, and
1855        :meth:`Publisher.send_all` cannot put more messages on the wire at once
1856        than :attr:`max_outstanding_publishes` allows however long the list it
1857        was given is.
1858
1859        :param exchange: where to publish, empty for the default exchange
1860        :param routing_key: what to publish under
1861        :param message: the message, encoded
1862        :returns: what the broker said
1863        :raises PublishingPausedError: when the broker has blocked this
1864            connection. Nothing was sent; retry once it unblocks
1865        :raises PublishError: when every permit is taken and none came free
1866            within :attr:`confirm_timeout`, or when the broker did not confirm
1867            this publish within it. The second may or may not have arrived
1868        """
1869        # Refused rather than queued, before a permit or a byte is spent. A
1870        # blocked broker stops reading the socket, so a publish sent now sits in
1871        # the client's write buffer with no confirm coming until the alarm
1872        # clears, then times out as a failure that may or may not have arrived.
1873        # Go and .NET refuse at the same point for the same reason. ``None``
1874        # means the state could not be read and is not treated as blocked.
1875        if self.blocked is True:
1876            reason = self.blocked_reason
1877            raise PublishingPausedError(
1878                message.message_id,
1879                exchange,
1880                routing_key,
1881                (
1882                    f"{self._blocked_detail(reason)}. Nothing was sent; back off and "
1883                    "retry once the broker unblocks"
1884                ),
1885            )
1886
1887        # Taken before the message is written and not after, which is the whole
1888        # point: a bound applied afterwards has already let the message into
1889        # memory. The permit is given back in the ``finally`` below on every
1890        # path there is — the publish returning, the publish raising, and this
1891        # task being cancelled while the broker is still thinking — because a
1892        # permit lost on any one of those is a connection that publishes a
1893        # thousand more messages and then stops for ever.
1894        try:
1895            await asyncio.wait_for(
1896                self._outstanding.acquire(), self._confirm_timeout.total_seconds()
1897            )
1898        except asyncio.TimeoutError as stalled:
1899            # Said rather than waited out. A publisher parked behind a broker
1900            # that has stopped answering is indistinguishable from a quiet
1901            # service, and this sentence is the one Java raises word for word so
1902            # that an operator reading a log has one thing to recognise.
1903            raise PublishError(
1904                message.message_id,
1905                exchange,
1906                routing_key,
1907                (
1908                    f"{self._max_outstanding} publishes are already waiting for a "
1909                    f"confirm and none completed within {self._confirm_timeout}. "
1910                    "The broker is not keeping up; publish more slowly rather than "
1911                    "buffering more."
1912                ),
1913            ) from stalled
1914
1915        self._in_flight_publishes += 1
1916        try:
1917            # Bounded as well, by the same timeout. RabbitMQ says a connection is
1918            # blocked only once it publishes, so the first publish after an alarm
1919            # is written and then held with no confirm until the alarm clears --
1920            # minutes, or never. Said here as a failure, not a refusal: it was
1921            # written, so it may have arrived. The publish after it sees the
1922            # block and is refused above. .NET bounds the same wait the same way.
1923            result = await asyncio.wait_for(
1924                self._transport.publish(exchange, routing_key, message),
1925                self._confirm_timeout.total_seconds(),
1926            )
1927        except asyncio.TimeoutError as unconfirmed:
1928            raise PublishError(
1929                message.message_id,
1930                exchange,
1931                routing_key,
1932                (
1933                    f"the broker did not confirm this publish within "
1934                    f"{self._confirm_timeout}. It may or may not have been stored, "
1935                    "so treat it as neither sent nor lost"
1936                ),
1937            ) from unconfirmed
1938        finally:
1939            self._in_flight_publishes -= 1
1940            self._outstanding.release()
1941
1942        # A nack is the broker declining to keep a message it was asked to take, and
1943        # it is raised here rather than returned.
1944        #
1945        # It used to be returned, and `confirmed` was read nowhere in this library
1946        # except a telemetry label -- so a caller who did not inspect the result
1947        # carried on believing the message had gone somewhere, and Java, .NET, Go and
1948        # Ruby all raised on the same event. Worse than the wrong belief: the outbox
1949        # relay removes a record because the publish did not raise, so a nack deleted
1950        # a record for a message the broker had refused. At-most-once, in the pattern
1951        # whose whole purpose is not losing anything.
1952        #
1953        # Checked here because this is the one place every publish in the library
1954        # comes through -- a Publisher, a retry rung, a dead letter, a replay, the
1955        # outbox -- so one check covers all of them, and anything that settles or
1956        # deletes on the strength of a publish returning now hears the refusal.
1957        #
1958        # Distinct from unroutable, which the Publisher path reports separately and
1959        # which sets `unroutable`: the broker could route this one and would not keep
1960        # it, and the two want different responses.
1961        #
1962        # So a returned message is passed back rather than raised here. The
1963        # RabbitMQ transport reports a Basic.Return as not confirmed as well as
1964        # not routed, and raising it as a nack hid ``routed`` from every caller
1965        # that reads it: a mandatory Publisher said "refused" rather than
1966        # "reached no queue", and the retry and dead-letter hops never reached
1967        # the fallbacks written for a queue that is not there.
1968        if not result.confirmed and result.routed:
1969            raise PublishError(
1970                message.message_id,
1971                exchange,
1972                routing_key,
1973                (
1974                    "the broker refused to confirm it. The message reached the broker "
1975                    "and the broker has not taken responsibility for it, so it must be "
1976                    "treated as not sent"
1977                ),
1978            )
1979
1980        return result

Sends bytes that are already encoded, with headers already rendered.

For the retry and dead-letter hops, and for anything else replaying a message recorded earlier: the payload's class may not exist any more, and re-encoding it would produce different bytes from the ones that were committed. Ordinary publishing goes through Publisher.

This is the one place the outstanding-publish bound is taken. Every publish in the library comes through here — a Publisher, a retry rung, a dead letter, a replay — so one permit counts them all, and Publisher.send_all() cannot put more messages on the wire at once than max_outstanding_publishes allows however long the list it was given is.

Parameters
  • exchange: where to publish, empty for the default exchange
  • routing_key: what to publish under
  • message: the message, encoded :returns: what the broker said
Raises
  • PublishingPausedError: when the broker has blocked this connection. Nothing was sent; retry once it unblocks
  • PublishError: when every permit is taken and none came free within confirm_timeout, or when the broker did not confirm this publish within it. The second may or may not have arrived
async def pull(self, queue: str) -> acemq_amqp.Delivery | None:
1982    async def pull(self, queue: str) -> Delivery | None:
1983        """Takes one message off a queue, or ``None`` when there is none waiting.
1984
1985        For tools rather than for services: it is a round trip per message where
1986        :meth:`consume` gets a stream. What it can do that a consumer cannot is
1987        say that a queue is empty, which is what anything working through a
1988        backlog and then stopping — a replay, a drain — has to know.
1989
1990        The delivery comes back unsettled, so the caller decides whether it is
1991        gone or goes back.
1992
1993        :param queue: what to read from
1994        :returns: the delivery, or ``None``
1995        """
1996        return await self._source().pull(queue)

Takes one message off a queue, or None when there is none waiting.

For tools rather than for services: it is a round trip per message where consume() gets a stream. What it can do that a consumer cannot is say that a queue is empty, which is what anything working through a backlog and then stopping — a replay, a drain — has to know.

The delivery comes back unsettled, so the caller decides whether it is gone or goes back.

Parameters
  • queue: what to read from :returns: the delivery, or None
async def queue_exists(self, queue: str) -> bool:
1998    async def queue_exists(self, queue: str) -> bool:
1999        """Whether a queue is on the broker, creating nothing."""
2000        return await self._admin().queue_exists(queue)

Whether a queue is on the broker, creating nothing.

async def message_count(self, queue: str) -> int:
2002    async def message_count(self, queue: str) -> int:
2003        """How many messages are waiting on a queue."""
2004        return await self._admin().message_count(queue)

How many messages are waiting on a queue.

async def delete_queue(self, queue: str) -> None:
2006    async def delete_queue(self, queue: str) -> None:
2007        """Removes a queue and every message still on it."""
2008        await self._admin().delete_queue(queue)

Removes a queue and every message still on it.

async def close(self, *, timeout: float | None = 20.0) -> bool:
2029    async def close(self, *, timeout: float | None = DEFAULT_DRAIN_TIMEOUT) -> bool:
2030        """Stops every consumer on this connection and releases it.
2031
2032        Consumers first, and their handlers given up to ``timeout`` to finish,
2033        so a message being worked on when this is called is settled rather than
2034        returned to the queue for somebody else to redo. The bound is one
2035        deadline for every handler of every consumer, not one each: they are
2036        all drained at once. A handler still running at the deadline is
2037        cancelled and its message left unsettled, for the broker to redeliver —
2038        see :meth:`Consumer.close`.
2039
2040        The connection is released whatever happens, including when the caller
2041        cancels closing; that cancellation is raised again afterwards.
2042
2043        :param timeout: seconds to wait for the running handlers; ``None``
2044            waits for as long as they take
2045        :returns: ``True`` if every handler finished, ``False`` if the time ran
2046            out first
2047        """
2048        if self._closed:
2049            return True
2050        self._closed = True
2051        try:
2052            drained = await asyncio.gather(
2053                *(consumer.close(timeout=timeout) for consumer in list(self._consumers)),
2054                return_exceptions=True,
2055            )
2056        finally:
2057            await self._transport.close()
2058        for outcome in drained:
2059            if isinstance(outcome, BaseException):
2060                raise outcome
2061        return all(drained)

Stops every consumer on this connection and releases it.

Consumers first, and their handlers given up to timeout to finish, so a message being worked on when this is called is settled rather than returned to the queue for somebody else to redo. The bound is one deadline for every handler of every consumer, not one each: they are all drained at once. A handler still running at the deadline is cancelled and its message left unsettled, for the broker to redeliver — see Consumer.close().

The connection is released whatever happens, including when the caller cancels closing; that cancellation is raised again afterwards.

Parameters
  • timeout: seconds to wait for the running handlers; None waits for as long as they take :returns: True if every handler finished, False if the time ran out first
@dataclass(frozen=True, slots=True)
class BrokerHealth:
2070@dataclass(frozen=True, slots=True)
2071class BrokerHealth:
2072    """A connection as a :class:`~acemq_amqp.telemetry.HealthCheck`.
2073
2074    So that a broker check and an application's own — a database, a downstream
2075    service — can be handed to
2076    :func:`~acemq_amqp.telemetry.aggregate_health` together, which is what a
2077    readiness endpoint actually needs.
2078
2079    A blocked broker comes back through here as **up, with the reason**, and
2080    nothing in between folds it into anything else: the aggregate takes the
2081    worst status it is given, so a check that reported back pressure as degraded
2082    would quietly degrade a report that had decided otherwise. The deadline is
2083    the same argument — :attr:`timeout` is shorter than the aggregate's, so that
2084    a broker which has stopped answering is described by this check rather than
2085    by the aggregate giving up on it.
2086
2087    :param connection: what to ask
2088    :param label: what to call it in a combined report
2089    :param timeout: how long to give the broker's answer. See
2090        :meth:`Connection.health`
2091    """
2092
2093    connection: Connection
2094    label: str = "broker"
2095    timeout: float = DEFAULT_HEALTH_TIMEOUT
2096
2097    @property
2098    def name(self) -> str:
2099        return self.label
2100
2101    async def check(self) -> HealthReport:
2102        return await self.connection.health(self.timeout)

A connection as a ~acemq_amqp.telemetry.HealthCheck.

So that a broker check and an application's own — a database, a downstream service — can be handed to ~acemq_amqp.telemetry.aggregate_health() together, which is what a readiness endpoint actually needs.

A blocked broker comes back through here as up, with the reason, and nothing in between folds it into anything else: the aggregate takes the worst status it is given, so a check that reported back pressure as degraded would quietly degrade a report that had decided otherwise. The deadline is the same argument — timeout is shorter than the aggregate's, so that a broker which has stopped answering is described by this check rather than by the aggregate giving up on it.

Parameters
  • connection: what to ask
  • label: what to call it in a combined report
  • timeout: how long to give the broker's answer. See Connection.health()
BrokerHealth( connection: Connection, label: str = 'broker', timeout: float = 3.0)
connection: Connection
label: str
timeout: float
name: str
2097    @property
2098    def name(self) -> str:
2099        return self.label
async def check(self) -> acemq_amqp.HealthReport:
2101    async def check(self) -> HealthReport:
2102        return await self.connection.health(self.timeout)
async def connect( url: str, *, codec: acemq_amqp.Codec | None = None, origin: str | None = None, retry: acemq_amqp.RetryPolicy | None = None, prefetch: int = 20, max_outstanding_publishes: int = 1000, confirm_timeout: datetime.timedelta = datetime.timedelta(seconds=10), security: acemq_amqp.Security | None = None, on_publish: Sequence[Callable[[acemq_amqp.PublishContext, Callable[[acemq_amqp.PublishContext], Awaitable[acemq_amqp.PublishResult]]], Awaitable[acemq_amqp.PublishResult]]] = (), on_consume: Sequence[Callable[[acemq_amqp.ConsumeContext, Callable[[acemq_amqp.ConsumeContext], Awaitable[acemq_amqp.Ack]]], Awaitable[acemq_amqp.Ack]]] = (), observer: acemq_amqp.Observer | None = None, **transport_options: Any) -> Connection:
2105async def connect(
2106    url: str,
2107    *,
2108    codec: Codec | None = None,
2109    origin: str | None = None,
2110    retry: RetryPolicy | None = None,
2111    prefetch: int = DEFAULT_PREFETCH,
2112    max_outstanding_publishes: int = DEFAULT_MAX_OUTSTANDING_PUBLISHES,
2113    confirm_timeout: timedelta = DEFAULT_CONFIRM_TIMEOUT,
2114    security: Security | None = None,
2115    on_publish: Sequence[PublishInterceptor] = (),
2116    on_consume: Sequence[ConsumeInterceptor] = (),
2117    observer: Observer | None = None,
2118    **transport_options: Any,
2119) -> Connection:
2120    """Opens a connection to a broker.
2121
2122    The URL's scheme picks the transport, and says whether the connection is
2123    encrypted: ``amqps://`` is, ``amqp://`` is not. Both need aio-pika, which is
2124    why it is imported here rather than by the package: a program that only
2125    reads AceMQ envelopes should not be made to install an AMQP client to import
2126    this library.
2127
2128    An ``amqps://`` URL is verified against the machine's trust store and will
2129    not speak anything older than TLS 1.2, with or without a ``security``. Pass
2130    one to name a different authority, to present a client certificate, or to
2131    supply the login separately from the URL — which is how a password stays out
2132    of a connection string that ends up in a log.
2133
2134    :param url: where the broker is
2135    :param codec: what publishers and consumers use unless they say otherwise
2136    :param origin: what to stamp on published messages
2137    :param retry: what consumers use unless they say otherwise
2138    :param prefetch: how many unacknowledged messages a consumer holds
2139    :param max_outstanding_publishes: how many publishes may be waiting for the
2140        broker at once, a thousand by default. See :class:`Connection`
2141    :param confirm_timeout: how long a publish waits for room before raising
2142    :param security: how to verify the broker and who to log in as. See
2143        :class:`~acemq_amqp.Security`
2144    :param on_publish: what to wrap every publish in, outermost first. See
2145        :mod:`acemq_amqp.interceptors`
2146    :param on_consume: what to wrap every handler in
2147    :param observer: where the numbers go. See :mod:`acemq_amqp.telemetry`
2148    :param transport_options: passed to the transport, which for RabbitMQ is
2149        :func:`aio_pika.connect_robust`
2150    :returns: the connection
2151    :raises SecurityError: when the security settings cannot be honoured, before
2152        anything is dialled
2153    """
2154    scheme = urlsplit(url).scheme
2155    if scheme not in ("amqp", "amqps"):
2156        raise AceMQError(
2157            f"acemq: no transport knows how to reach {scheme or url!r}; "
2158            "this library speaks amqp:// and amqps://"
2159        )
2160
2161    # Resolved here rather than in the transport, so that a missing certificate
2162    # or an unset password variable is an exception from connect() with the
2163    # setting named in it, rather than a handshake failure from somewhere in
2164    # aio-pika that says only that the socket closed.
2165    settings = security or Security()
2166    url = settings.applied_to(url)
2167    # The caller's own options win: transport_options is the escape hatch for
2168    # everything this library does not model, and a Security built from defaults
2169    # should not quietly overrule an ssl_context somebody passed by hand.
2170    transport_options = {**settings.transport_options(url), **transport_options}
2171
2172    try:
2173        from .rabbitmq import RabbitMQTransport
2174    except ImportError as missing:  # pragma: no cover - depends on how it was installed
2175        raise AceMQError(
2176            "acemq: reaching a broker needs aio-pika, which is an optional extra. "
2177            'Install it with pip install "acemq-amqp[rabbitmq]"'
2178        ) from missing
2179
2180    transport = await RabbitMQTransport.connect(url, **transport_options)
2181    return Connection(
2182        transport,
2183        codec=codec,
2184        origin=origin,
2185        retry=retry,
2186        prefetch=prefetch,
2187        max_outstanding_publishes=max_outstanding_publishes,
2188        confirm_timeout=confirm_timeout,
2189        on_publish=on_publish,
2190        on_consume=on_consume,
2191        observer=observer,
2192    )

Opens a connection to a broker.

The URL's scheme picks the transport, and says whether the connection is encrypted: amqps:// is, amqp:// is not. Both need aio-pika, which is why it is imported here rather than by the package: a program that only reads AceMQ envelopes should not be made to install an AMQP client to import this library.

An amqps:// URL is verified against the machine's trust store and will not speak anything older than TLS 1.2, with or without a security. Pass one to name a different authority, to present a client certificate, or to supply the login separately from the URL — which is how a password stays out of a connection string that ends up in a log.

Parameters
  • url: where the broker is
  • codec: what publishers and consumers use unless they say otherwise
  • origin: what to stamp on published messages
  • retry: what consumers use unless they say otherwise
  • prefetch: how many unacknowledged messages a consumer holds
  • max_outstanding_publishes: how many publishes may be waiting for the broker at once, a thousand by default. See Connection
  • confirm_timeout: how long a publish waits for room before raising
  • security: how to verify the broker and who to log in as. See ~acemq_amqp.Security
  • on_publish: what to wrap every publish in, outermost first. See acemq_amqp.interceptors
  • on_consume: what to wrap every handler in
  • observer: where the numbers go. See acemq_amqp.telemetry
  • transport_options: passed to the transport, which for RabbitMQ is aio_pika.connect_robust() :returns: the connection
Raises
  • SecurityError: when the security settings cannot be honoured, before anything is dialled
def default_origin() -> str:
2195def default_origin() -> str:
2196    """``acemq@{hostname}``, which names the machine but not the service.
2197
2198    Enough to tell two pods apart in a log, which is what an origin is for, and
2199    deliberately not a guess at the service name: a wrong service name in a
2200    message that has already been published is worse than an honest hostname.
2201    """
2202    return f"acemq@{socket.gethostname()}"

acemq@{hostname}, which names the machine but not the service.

Enough to tell two pods apart in a log, which is what an origin is for, and deliberately not a guess at the service name: a wrong service name in a message that has already been published is worse than an honest hostname.