Skip to content

Messages & Settlement

RabbitMessage

RabbitMessage

Rich incoming message with transport-aware settlement.

The message object wraps raw AMQP delivery data and provides: - Typed access to headers, properties, routing info - Sync and async ack/nack/reject methods - Idempotent settlement (double-ack is a no-op) - Topic wildcard path extraction

Source code in src/rabbitkit/core/message.py
class RabbitMessage:
    """Rich incoming message with transport-aware settlement.

    The message object wraps raw AMQP delivery data and provides:
    - Typed access to headers, properties, routing info
    - Sync and async ack/nack/reject methods
    - Idempotent settlement (double-ack is a no-op)
    - Topic wildcard path extraction
    """

    __slots__ = (
        "_ack_async_fn",
        "_ack_fn",
        "_channel_alive",
        "_disposition",
        "_nack_async_fn",
        "_nack_fn",
        "_reject_async_fn",
        "_reject_fn",
        "_settle_unknown",
        "_settlement_metric_once",
        "_wire_body",
        "_wire_content_encoding",
        "app_id",
        "body",
        "consumer_tag",
        "content_encoding",
        "content_type",
        "correlation_id",
        "delivery_mode",
        "delivery_tag",
        "exchange",
        "expiration",
        "headers",
        "message_id",
        "path",
        "priority",
        "raw_message",
        "redelivered",
        "reply_to",
        "routing_key",
        "timestamp",
        "type",
        "user_id",
    )

    def __init__(
        self,
        *,
        body: bytes,
        headers: dict[str, Any] | None = None,
        message_id: str | None = None,
        correlation_id: str | None = None,
        reply_to: str | None = None,
        content_type: str | None = None,
        content_encoding: str | None = None,
        timestamp: datetime | None = None,
        type: str | None = None,  # noqa: A002 — AMQP property name
        app_id: str | None = None,
        priority: int | None = None,
        expiration: str | None = None,
        user_id: str | None = None,
        delivery_mode: int | None = None,
        routing_key: str = "",
        exchange: str = "",
        delivery_tag: int | None = None,
        redelivered: bool = False,
        consumer_tag: str | None = None,
        path: dict[str, str] | None = None,
        raw_message: Any = None,
    ) -> None:
        self.body = body
        self.headers: dict[str, Any] = headers or {}
        self.message_id = message_id
        self.correlation_id = correlation_id
        self.reply_to = reply_to
        self.content_type = content_type
        self.content_encoding = content_encoding
        self.timestamp = timestamp
        self.type = type
        self.app_id = app_id
        self.priority = priority
        self.expiration = expiration
        self.user_id = user_id
        # 1 = transient, 2 = persistent, None = the publisher set none
        # (the broker treats that as transient).
        self.delivery_mode = delivery_mode
        self.routing_key = routing_key
        self.exchange = exchange
        self.delivery_tag = delivery_tag
        self.redelivered = redelivered
        self.consumer_tag = consumer_tag
        self.path: dict[str, str] = path or {}
        self.raw_message = raw_message
        # The body and encoding as delivered, before any on_receive hook
        # (decompression, decryption) rewrites them: retry and DLQ copies
        # republish these, so the copy decodes like the original.
        self._wire_body = body
        self._wire_content_encoding = content_encoding

        # Transport-injected settlement functions (internal)
        self._ack_fn: Callable[[], None] | None = None
        self._ack_async_fn: Callable[[], Awaitable[None]] | None = None
        self._nack_fn: Callable[[bool], None] | None = None
        self._nack_async_fn: Callable[[bool], Awaitable[None]] | None = None
        self._reject_fn: Callable[[bool], None] | None = None
        self._reject_async_fn: Callable[[bool], Awaitable[None]] | None = None
        self._disposition: str = "pending"
        # True when a claimed async settlement's transport call raised
        # or was cancelled -- the frame may or may not have reached the broker.
        self._settle_unknown = False
        # One-element token taken (``pop()``) by the first settlement-metric
        # emission when two threads may report the same delivery (the sync
        # processing deadline and its late handler); None = no such race.
        self._settlement_metric_once: list[None] | None = None
        # Transport-injected liveness probe for the channel this delivery
        # arrived on (``lambda: channel.is_open``). Delivery tags are only
        # meaningful on their own channel generation; ``ack_many`` /
        # ``nack_many`` consult this to report a STALE handle instead of
        # issuing a tag onto a rebuilt channel (where it would settle a
        # DIFFERENT message). ``None`` = unknown (TestBroker, hand-built).
        self._channel_alive: Callable[[], bool] | None = None

    @property
    def wire_body(self) -> bytes:
        """The body exactly as the broker delivered it.

        ``body`` may have been rewritten by an ``on_receive`` hook
        (``CompressionMiddleware`` decompresses it in place); this is the
        original, still matching :attr:`wire_content_encoding`.
        """
        return self._wire_body

    @property
    def wire_content_encoding(self) -> str | None:
        """``content_encoding`` exactly as the broker delivered it."""
        return self._wire_content_encoding

    @property
    def stream_offset(self) -> int | None:
        """This delivery's offset in a stream queue, else None.

        RabbitMQ stamps every delivery from a stream with an
        ``x-stream-offset`` header (overwriting any value a publisher set).
        On a classic or quorum queue the header is whatever the publisher
        sent, so only read this for deliveries from a stream.
        """
        value = self.headers.get("x-stream-offset")
        if isinstance(value, bool) or not isinstance(value, int):
            return None
        return int(value)

    @property
    def is_settled(self) -> bool:
        """True if the message has been acked, nacked, or rejected."""
        return self._disposition != "pending"

    @property
    def disposition(self) -> str:
        """Final settlement state: "pending", "acked", "nacked", or "rejected" (M2)."""
        return self._disposition

    @property
    def settlement_outcome_unknown(self) -> bool:
        """True if an async settlement was claimed but its send raised or was cancelled.

        The ack/nack/reject frame may or may not have reached the broker.
        ``disposition`` keeps the claimed value and no other settlement is
        sent for this delivery; if the frame was lost, the broker redelivers
        the message when its channel closes (at-least-once).
        """
        return self._settle_unknown

    @property
    def channel_alive(self) -> bool | None:
        """Whether the channel this delivery arrived on is still open.

        ``None`` when the transport did not wire a probe (in-memory
        ``TestBroker``, hand-constructed messages). ``False`` means the
        delivery tag is STALE — the broker has already (or will) redeliver
        this message on a new channel and settling it here would be a
        protocol error or, worse, settle a different message.
        """
        if self._channel_alive is None:
            return None
        try:
            return bool(self._channel_alive())
        except Exception:
            return False

    # ── Sync settlement ───────────────────────────────────────────────────

    def ack(self) -> None:
        """Synchronous ack. Raises SettlementError on async-only transport.

        Sets disposition only after the transport call succeeds, so a failed
        ack (channel closed, frame error) leaves the message unsettled and the
        exception propagates to the recovery loop instead of being swallowed.
        """
        if self._disposition != "pending":
            return  # idempotent guard
        if self._ack_fn is None:
            msg = "Cannot sync-ack an async transport message. Use await msg.ack_async()."
            raise SettlementError(msg)
        self._ack_fn()  # may raise — disposition stays "pending" on failure
        self._disposition = "acked"

    def nack(self, requeue: bool = True) -> None:
        """Synchronous nack. Raises SettlementError on async-only transport."""
        if self._disposition != "pending":
            return
        if self._nack_fn is None:
            msg = "Cannot sync-nack an async transport message. Use await msg.nack_async()."
            raise SettlementError(msg)
        self._nack_fn(requeue)
        self._disposition = "nacked"

    def reject(self, requeue: bool = False) -> None:
        """Synchronous reject. Raises SettlementError on async-only transport."""
        if self._disposition != "pending":
            return
        if self._reject_fn is None:
            msg = "Cannot sync-reject an async transport message. Use await msg.reject_async()."
            raise SettlementError(msg)
        self._reject_fn(requeue)
        self._disposition = "rejected"

    # ── Async settlement ──────────────────────────────────────────────────
    #
    # the async variants CLAIM the settlement before awaiting the
    # transport. The old guard checked ``_disposition`` and set it only after
    # the await, so two coroutines (a concurrent ack/nack, or ``stop()``
    # nacking a handler that was cancelled mid-ack) could both pass the check
    # and send two frames for one delivery tag -- the broker answers the
    # second with PRECONDITION_FAILED ("unknown delivery tag"), which closes
    # the channel and redelivers every unacked message on it. Check-and-claim
    # has no ``await`` in between, so it is atomic on the event loop.
    #
    # If the send then raises or is cancelled, the frame may or may not have
    # reached the broker. The claim is kept (a second, different frame could
    # contradict one that landed) and ``settlement_outcome_unknown`` turns
    # True; if the frame did not land, the broker redelivers the message when
    # the channel closes. The exception still propagates.

    async def _settle_async(
        self,
        disposition: str,
        async_fn: Callable[..., Awaitable[None]] | None,
        sync_fn: Callable[..., None] | None,
        args: tuple[bool, ...],
        verb: str,
    ) -> None:
        if self._disposition != "pending":
            return  # already claimed: never a second frame for this delivery
        if async_fn is None and sync_fn is None:
            raise SettlementError(f"Cannot async-{verb}: no settlement fn set. Use msg.{verb}() on a sync transport.")
        self._disposition = disposition  # claim BEFORE any await
        try:
            if async_fn is not None:
                await async_fn(*args)
            else:
                assert sync_fn is not None  # narrowed by the check above
                sync_fn(*args)
        except BaseException:
            self._settle_unknown = True
            raise

    async def ack_async(self) -> None:
        """Async ack. Falls back to sync if async fn not set.

        The settlement is claimed before the transport call (see
        ``settlement_outcome_unknown``): a concurrent or later
        ``ack_async``/``nack_async``/``reject_async`` is a no-op.
        """
        await self._settle_async("acked", self._ack_async_fn, self._ack_fn, (), "ack")

    async def nack_async(self, requeue: bool = True) -> None:
        """Async nack. Falls back to sync if async fn not set. Claims first (see ``ack_async``)."""
        await self._settle_async("nacked", self._nack_async_fn, self._nack_fn, (requeue,), "nack")

    async def reject_async(self, requeue: bool = False) -> None:
        """Async reject. Falls back to sync if async fn not set. Claims first (see ``ack_async``)."""
        await self._settle_async("rejected", self._reject_async_fn, self._reject_fn, (requeue,), "reject")

Attributes

wire_body: bytes property

The body exactly as the broker delivered it.

body may have been rewritten by an on_receive hook (CompressionMiddleware decompresses it in place); this is the original, still matching :attr:wire_content_encoding.

wire_content_encoding: str | None property

content_encoding exactly as the broker delivered it.

stream_offset: int | None property

This delivery's offset in a stream queue, else None.

RabbitMQ stamps every delivery from a stream with an x-stream-offset header (overwriting any value a publisher set). On a classic or quorum queue the header is whatever the publisher sent, so only read this for deliveries from a stream.

is_settled: bool property

True if the message has been acked, nacked, or rejected.

disposition: str property

Final settlement state: "pending", "acked", "nacked", or "rejected" (M2).

settlement_outcome_unknown: bool property

True if an async settlement was claimed but its send raised or was cancelled.

The ack/nack/reject frame may or may not have reached the broker. disposition keeps the claimed value and no other settlement is sent for this delivery; if the frame was lost, the broker redelivers the message when its channel closes (at-least-once).

channel_alive: bool | None property

Whether the channel this delivery arrived on is still open.

None when the transport did not wire a probe (in-memory TestBroker, hand-constructed messages). False means the delivery tag is STALE — the broker has already (or will) redeliver this message on a new channel and settling it here would be a protocol error or, worse, settle a different message.

Methods:

ack() -> None

Synchronous ack. Raises SettlementError on async-only transport.

Sets disposition only after the transport call succeeds, so a failed ack (channel closed, frame error) leaves the message unsettled and the exception propagates to the recovery loop instead of being swallowed.

Source code in src/rabbitkit/core/message.py
def ack(self) -> None:
    """Synchronous ack. Raises SettlementError on async-only transport.

    Sets disposition only after the transport call succeeds, so a failed
    ack (channel closed, frame error) leaves the message unsettled and the
    exception propagates to the recovery loop instead of being swallowed.
    """
    if self._disposition != "pending":
        return  # idempotent guard
    if self._ack_fn is None:
        msg = "Cannot sync-ack an async transport message. Use await msg.ack_async()."
        raise SettlementError(msg)
    self._ack_fn()  # may raise — disposition stays "pending" on failure
    self._disposition = "acked"

nack(requeue: bool = True) -> None

Synchronous nack. Raises SettlementError on async-only transport.

Source code in src/rabbitkit/core/message.py
def nack(self, requeue: bool = True) -> None:
    """Synchronous nack. Raises SettlementError on async-only transport."""
    if self._disposition != "pending":
        return
    if self._nack_fn is None:
        msg = "Cannot sync-nack an async transport message. Use await msg.nack_async()."
        raise SettlementError(msg)
    self._nack_fn(requeue)
    self._disposition = "nacked"

reject(requeue: bool = False) -> None

Synchronous reject. Raises SettlementError on async-only transport.

Source code in src/rabbitkit/core/message.py
def reject(self, requeue: bool = False) -> None:
    """Synchronous reject. Raises SettlementError on async-only transport."""
    if self._disposition != "pending":
        return
    if self._reject_fn is None:
        msg = "Cannot sync-reject an async transport message. Use await msg.reject_async()."
        raise SettlementError(msg)
    self._reject_fn(requeue)
    self._disposition = "rejected"

ack_async() -> None async

Async ack. Falls back to sync if async fn not set.

The settlement is claimed before the transport call (see settlement_outcome_unknown): a concurrent or later ack_async/nack_async/reject_async is a no-op.

Source code in src/rabbitkit/core/message.py
async def ack_async(self) -> None:
    """Async ack. Falls back to sync if async fn not set.

    The settlement is claimed before the transport call (see
    ``settlement_outcome_unknown``): a concurrent or later
    ``ack_async``/``nack_async``/``reject_async`` is a no-op.
    """
    await self._settle_async("acked", self._ack_async_fn, self._ack_fn, (), "ack")

nack_async(requeue: bool = True) -> None async

Async nack. Falls back to sync if async fn not set. Claims first (see ack_async).

Source code in src/rabbitkit/core/message.py
async def nack_async(self, requeue: bool = True) -> None:
    """Async nack. Falls back to sync if async fn not set. Claims first (see ``ack_async``)."""
    await self._settle_async("nacked", self._nack_async_fn, self._nack_fn, (requeue,), "nack")

reject_async(requeue: bool = False) -> None async

Async reject. Falls back to sync if async fn not set. Claims first (see ack_async).

Source code in src/rabbitkit/core/message.py
async def reject_async(self, requeue: bool = False) -> None:
    """Async reject. Falls back to sync if async fn not set. Claims first (see ``ack_async``)."""
    await self._settle_async("rejected", self._reject_async_fn, self._reject_fn, (requeue,), "reject")

MessageEnvelope

MessageEnvelope dataclass

Outgoing message envelope.

NOTE: AMQP header values are limited to: str, int, float, bool, bytes, datetime, Decimal, list/dict of these, or None. Arbitrary Python objects (sets, custom classes) will raise at publish time. Transport validates header values before sending.

Source code in src/rabbitkit/core/types.py
@dataclass(frozen=True, slots=True)
class MessageEnvelope:
    """Outgoing message envelope.

    NOTE: AMQP header values are limited to:
    str, int, float, bool, bytes, datetime, Decimal, list/dict of these, or None.
    Arbitrary Python objects (sets, custom classes) will raise at publish time.
    Transport validates header values before sending.
    """

    routing_key: str
    body: bytes
    exchange: str = ""
    headers: dict[str, Any] = field(default_factory=dict)
    message_id: str = field(default_factory=lambda: str(uuid.uuid4()))
    correlation_id: str | None = None
    reply_to: str | None = None
    timestamp: datetime | None = None
    content_type: str = "application/json"
    content_encoding: str | None = None
    expiration: str | None = None
    priority: int | None = None
    mandatory: bool = False
    delivery_mode: int = 2  # 1=transient, 2=persistent
    type: str | None = None
    user_id: str | None = None
    app_id: str | None = None

    def __post_init__(self) -> None:
        # Catches an oversized routing_key/exchange at construction time --
        # the same choke point every publish (broker.publish, retry
        # republish, DLQ replay, batch) goes through -- instead of an
        # opaque broker connection error later.
        validate_amqp_shortstr("routing_key", self.routing_key)
        validate_amqp_shortstr("exchange", self.exchange)

InboundMessageTooLargeError

Bases: InvalidMessageError

A delivery's raw body exceeds ConsumerConfig.max_body_bytes.

INVALID_MESSAGE: the delivery is dead-lettered without running any middleware or the handler.

Source code in src/rabbitkit/core/errors.py
class InboundMessageTooLargeError(InvalidMessageError):
    """A delivery's raw body exceeds ``ConsumerConfig.max_body_bytes``.

    ``INVALID_MESSAGE``: the delivery is dead-lettered without running any
    middleware or the handler.
    """

    def __init__(self, size: int, limit: int) -> None:
        super().__init__(f"Delivered body ({size} bytes) exceeds ConsumerConfig.max_body_bytes ({limit})")
        self.size = size
        self.limit = limit

Reserved headers

strip_reserved_headers(headers: Mapping[str, Any], extra: Iterable[str] = ()) -> dict[str, Any] | None

headers without the reserved ones (and any in extra), or None when nothing had to be removed (the caller keeps its object, no copy).

Source code in src/rabbitkit/core/reserved_headers.py
def strip_reserved_headers(headers: Mapping[str, Any], extra: Iterable[str] = ()) -> dict[str, Any] | None:
    """*headers* without the reserved ones (and any in *extra*), or ``None``
    when nothing had to be removed (the caller keeps its object, no copy)."""
    extra_set = frozenset(extra)
    if not any(name in RESERVED_HEADERS or name in extra_set for name in headers):
        return None
    return {k: v for k, v in headers.items() if k not in RESERVED_HEADERS and k not in extra_set}

AckPolicy

AckPolicy

Bases: str, Enum

Message acknowledgement policies.

See Contract 1 in the plan for exact semantics: - AUTO: success→ack, exception→classify→nack/reject - MANUAL: handler owns ack/nack/reject entirely - NACK_ON_ERROR: success→ack, exception→nack(requeue=False) - ACK_FIRST: ack BEFORE handler runs (at-most-once)

Source code in src/rabbitkit/core/types.py
class AckPolicy(str, Enum):
    """Message acknowledgement policies.

    See Contract 1 in the plan for exact semantics:
    - AUTO: success→ack, exception→classify→nack/reject
    - MANUAL: handler owns ack/nack/reject entirely
    - NACK_ON_ERROR: success→ack, exception→nack(requeue=False)
    - ACK_FIRST: ack BEFORE handler runs (at-most-once)
    """

    AUTO = "auto"
    MANUAL = "manual"
    NACK_ON_ERROR = "nack_on_error"
    ACK_FIRST = "ack_first"

AckStrategy

AckStrategy

Bases: Protocol

Settlement strategy for an AckPolicy.

Each strategy owns the success-path ack and the error-path settlement. Handler-raised AckMessage / NackMessage / RejectMessage are NOT policy-driven and stay in the pipeline.

See Contract 1 in the plan for per-policy semantics.

Source code in src/rabbitkit/core/types.py
@runtime_checkable
class AckStrategy(Protocol):
    """Settlement strategy for an ``AckPolicy``.

    Each strategy owns the success-path ack and the error-path settlement.
    Handler-raised ``AckMessage`` / ``NackMessage`` / ``RejectMessage`` are
    NOT policy-driven and stay in the pipeline.

    See Contract 1 in the plan for per-policy semantics.
    """

    @property
    def acks_first(self) -> bool:
        """True when the message is acked BEFORE the handler runs (ACK_FIRST)."""
        ...

    def on_success(self, msg: RabbitMessage) -> None:
        """Settle the message after a successful handler invocation."""
        ...

    def on_error(self, msg: RabbitMessage, exc: Exception) -> None:
        """Settle the message after an unhandled handler exception."""
        ...

Attributes

acks_first: bool property

True when the message is acked BEFORE the handler runs (ACK_FIRST).

Methods:

on_success(msg: RabbitMessage) -> None

Settle the message after a successful handler invocation.

Source code in src/rabbitkit/core/types.py
def on_success(self, msg: RabbitMessage) -> None:
    """Settle the message after a successful handler invocation."""
    ...

on_error(msg: RabbitMessage, exc: Exception) -> None

Settle the message after an unhandled handler exception.

Source code in src/rabbitkit/core/types.py
def on_error(self, msg: RabbitMessage, exc: Exception) -> None:
    """Settle the message after an unhandled handler exception."""
    ...

PublishOutcome / PublishStatus

PublishOutcome dataclass

Result of a publish operation.

reason is a bounded code from :class:PublishReason saying why a non-success status happened (None when the transport did not classify it). reply_code / reply_text carry the broker's basic.return fields for a RETURNED publish (e.g. 312 / "NO_ROUTE") and the channel-close fields for a refused one.

Source code in src/rabbitkit/core/types.py
@dataclass(frozen=True, slots=True, repr=False)
class PublishOutcome:
    """Result of a publish operation.

    ``reason`` is a bounded code from :class:`PublishReason` saying why a
    non-success status happened (``None`` when the transport did not
    classify it). ``reply_code`` / ``reply_text`` carry the broker's
    ``basic.return`` fields for a RETURNED publish (e.g. ``312`` /
    ``"NO_ROUTE"``) and the channel-close fields for a refused one.
    """

    status: PublishStatus
    delivery_tag: int | None = None
    exchange: str = ""
    routing_key: str = ""
    error: BaseException | None = None
    timestamp: datetime = field(default_factory=lambda: datetime.now(UTC))
    reason: str | None = None
    reply_code: int | None = None
    reply_text: str | None = None

    def __repr__(self) -> str:
        # Hand-written so a broken error repr (see safe_exception_repr) can't
        # make the outcome itself unprintable: raise_for_status() builds its
        # message from this, and used to raise AttributeError on aiormq 7.
        error = None if self.error is None else safe_exception_repr(self.error)
        extra = ""
        if self.reason is not None:
            extra += f", reason={self.reason!r}"
        if self.reply_code is not None:
            extra += f", reply_code={self.reply_code!r}, reply_text={self.reply_text!r}"
        return (
            f"PublishOutcome(status={self.status!r}, delivery_tag={self.delivery_tag!r}, "
            f"exchange={self.exchange!r}, routing_key={self.routing_key!r}, error={error}, "
            f"timestamp={self.timestamp!r}{extra})"
        )

    @property
    def is_unknown(self) -> bool:
        """True when the broker may or may not have the message: ``UNKNOWN``
        or ``TIMEOUT`` (a confirm timeout is one kind of unknown outcome).

        Republish only with the same ``message_id`` so consumers can
        deduplicate.
        """
        return self.status in (PublishStatus.UNKNOWN, PublishStatus.TIMEOUT)

    @property
    def ok(self) -> bool:
        """True if the publish did not fail -- CONFIRMED (broker
        acknowledged it) or SENT (fire-and-forget, confirm_delivery=False --
        written to the socket but never broker-confirmed).

        M4: if you specifically need to know the broker actually confirmed
        the message (e.g. before treating a republish as durable enough to
        settle/discard the original), check ``status ==
        PublishStatus.CONFIRMED`` directly -- ``.ok`` alone can't
        distinguish "confirmed" from "sent, unconfirmed."
        """
        return self.status in (PublishStatus.CONFIRMED, PublishStatus.SENT)

    def raise_for_status(self) -> PublishOutcome:
        """Raise ``PublishError`` if the publish failed; else return self (M1).

        ``broker.publish()`` never raises — it returns this outcome so a
        failed publish (NACKED / TIMEOUT / RETURNED / ERROR / NOT_SENT /
        UNKNOWN) can't be lost by
        code that simply ignores the return value. Callers who prefer
        exceptions opt in::

            broker.publish(envelope).raise_for_status()

        Chains so ``outcome = broker.publish(...).raise_for_status()`` works.
        """
        if not self.ok:
            from rabbitkit.core.errors import PublishError

            raise PublishError(self)
        return self

    @property
    def classification(self) -> ClassifiedError | None:
        """Best-effort severity/reason for ``self.error``, via the existing
        ``classify_error()`` (production-hardening item 5).

        Deliberately NOT a new ``PublishStatus`` enum member: growing that
        small, closed "what happened" set (CONFIRMED/SENT/NACKED/TIMEOUT/
        RETURNED/ERROR) risks breaking exhaustive match/if-chains callers
        may have written against it, for a "why" signal better served by
        reusing the classification machinery already wired into the
        consume/retry path (``core/errors.py``) rather than duplicating it.
        A lazy import avoids a module-level cycle (``core/errors.py``
        already imports from this module) — same pattern as
        :meth:`raise_for_status`.

        ``None`` when there's nothing to classify: a non-ERROR status, or
        an ERROR outcome that (unusually) captured no exception.
        """
        if self.status is not PublishStatus.ERROR or self.error is None:
            return None
        from rabbitkit.core.errors import classify_error

        return classify_error(self.error)

Attributes

is_unknown: bool property

True when the broker may or may not have the message: UNKNOWN or TIMEOUT (a confirm timeout is one kind of unknown outcome).

Republish only with the same message_id so consumers can deduplicate.

ok: bool property

True if the publish did not fail -- CONFIRMED (broker acknowledged it) or SENT (fire-and-forget, confirm_delivery=False -- written to the socket but never broker-confirmed).

M4: if you specifically need to know the broker actually confirmed the message (e.g. before treating a republish as durable enough to settle/discard the original), check status == PublishStatus.CONFIRMED directly -- .ok alone can't distinguish "confirmed" from "sent, unconfirmed."

classification: ClassifiedError | None property

Best-effort severity/reason for self.error, via the existing classify_error() (production-hardening item 5).

Deliberately NOT a new PublishStatus enum member: growing that small, closed "what happened" set (CONFIRMED/SENT/NACKED/TIMEOUT/ RETURNED/ERROR) risks breaking exhaustive match/if-chains callers may have written against it, for a "why" signal better served by reusing the classification machinery already wired into the consume/retry path (core/errors.py) rather than duplicating it. A lazy import avoids a module-level cycle (core/errors.py already imports from this module) — same pattern as :meth:raise_for_status.

None when there's nothing to classify: a non-ERROR status, or an ERROR outcome that (unusually) captured no exception.

Methods:

raise_for_status() -> PublishOutcome

Raise PublishError if the publish failed; else return self (M1).

broker.publish() never raises — it returns this outcome so a failed publish (NACKED / TIMEOUT / RETURNED / ERROR / NOT_SENT / UNKNOWN) can't be lost by code that simply ignores the return value. Callers who prefer exceptions opt in::

broker.publish(envelope).raise_for_status()

Chains so outcome = broker.publish(...).raise_for_status() works.

Source code in src/rabbitkit/core/types.py
def raise_for_status(self) -> PublishOutcome:
    """Raise ``PublishError`` if the publish failed; else return self (M1).

    ``broker.publish()`` never raises — it returns this outcome so a
    failed publish (NACKED / TIMEOUT / RETURNED / ERROR / NOT_SENT /
    UNKNOWN) can't be lost by
    code that simply ignores the return value. Callers who prefer
    exceptions opt in::

        broker.publish(envelope).raise_for_status()

    Chains so ``outcome = broker.publish(...).raise_for_status()`` works.
    """
    if not self.ok:
        from rabbitkit.core.errors import PublishError

        raise PublishError(self)
    return self

PublishStatus

Bases: str, Enum

Result status of a publish operation.

Source code in src/rabbitkit/core/types.py
class PublishStatus(str, Enum):
    """Result status of a publish operation."""

    CONFIRMED = "confirmed"
    #: M4: fire-and-forget publish (PublisherConfig.confirm_delivery=False)
    #: -- written to the socket, but the broker never acknowledged it.
    #: Distinct from CONFIRMED so code that specifically needs a real
    #: broker ack (e.g. deciding whether it's safe to ack/discard a source
    #: message after republishing it, as retry/result publishing do) can
    #: tell the two apart via ``.status`` instead of being told "confirmed"
    #: when nothing was actually confirmed.
    SENT = "sent"
    NACKED = "nacked"
    #: No publisher confirm arrived within the confirm timeout (or the
    #: per-call ``timeout``). The frames left the client, so the broker may
    #: or may not have the message: a flavour of :attr:`UNKNOWN`
    #: (``PublishOutcome.is_unknown`` is True for both).
    TIMEOUT = "timeout"
    RETURNED = "returned"
    #: An unexpected, unclassified failure. Every failure the transport can
    #: classify is reported as NOT_SENT, UNKNOWN, TIMEOUT, NACKED or RETURNED
    #: instead; ``PublishOutcome.reason`` says which ERROR it was when known
    #: (e.g. ``exchange_not_found``).
    ERROR = "error"
    #: The message definitely never left the client: admission timed out,
    #: the publisher is closed, no connection or channel was available, or a
    #: flow-control policy dropped it. Safe to publish again.
    NOT_SENT = "not_sent"
    #: The frames may have left the client but no confirm, return or nack
    #: was observed (connection or channel lost mid-publish, shutdown).
    #: Republish only with the SAME ``message_id`` so consumers can
    #: deduplicate; the library never republishes on its own.
    UNKNOWN = "unknown"

PublishReason

Bounded PublishOutcome.reason codes (snake_case, safe as a metric label).

Plain string constants rather than an Enum so outcome.reason is an ordinary str ("admission_timeout"), whatever produced it.

Source code in src/rabbitkit/core/types.py
class PublishReason:
    """Bounded ``PublishOutcome.reason`` codes (snake_case, safe as a metric label).

    Plain string constants rather than an Enum so ``outcome.reason`` is an
    ordinary ``str`` (``"admission_timeout"``), whatever produced it.
    """

    # NOT_SENT
    ADMISSION_TIMEOUT = "admission_timeout"
    PUBLISHER_CLOSED = "publisher_closed"
    NOT_CONNECTED = "not_connected"
    CHANNEL_UNAVAILABLE = "channel_unavailable"
    EXCEEDS_BYTE_BUDGET = "exceeds_max_in_flight_bytes"
    BACKPRESSURE_DROPPED = "backpressure_dropped"
    #: The caller was cancelled before its message left the client.
    CANCELLED = "cancelled"
    # UNKNOWN
    CONNECTION_LOST = "connection_lost"
    CHANNEL_CLOSED = "channel_closed"
    SHUTDOWN = "shutdown"
    # TIMEOUT
    CONFIRM_TIMEOUT = "confirm_timeout"
    PUBLISH_TIMEOUT = "publish_timeout"
    # RETURNED / NACKED
    RETURNED = "returned"
    NACKED = "nacked"
    # ERROR
    EXCHANGE_NOT_FOUND = "exchange_not_found"
    ACCESS_REFUSED = "access_refused"
    PRECONDITION_FAILED = "precondition_failed"
    INVALID_ENVELOPE = "invalid_envelope"
    PUBLISH_ERROR = "publish_error"

    ALL: frozenset[str] = frozenset(
        {
            ADMISSION_TIMEOUT,
            PUBLISHER_CLOSED,
            NOT_CONNECTED,
            CHANNEL_UNAVAILABLE,
            EXCEEDS_BYTE_BUDGET,
            BACKPRESSURE_DROPPED,
            CONNECTION_LOST,
            CHANNEL_CLOSED,
            SHUTDOWN,
            CANCELLED,
            CONFIRM_TIMEOUT,
            PUBLISH_TIMEOUT,
            RETURNED,
            NACKED,
            EXCHANGE_NOT_FOUND,
            ACCESS_REFUSED,
            PRECONDITION_FAILED,
            INVALID_ENVELOPE,
            PUBLISH_ERROR,
        }
    )

Settlement exceptions

AckMessage

Bases: Exception

Raise from handler to ack the message.

Source code in src/rabbitkit/core/message.py
class AckMessage(Exception):
    """Raise from handler to ack the message."""

NackMessage

Bases: Exception

Raise from handler to nack the message.

Source code in src/rabbitkit/core/message.py
class NackMessage(Exception):
    """Raise from handler to nack the message."""

    def __init__(self, requeue: bool = True) -> None:
        super().__init__()
        self.requeue = requeue

RejectMessage

Bases: Exception

Raise from handler to reject the message.

Source code in src/rabbitkit/core/message.py
class RejectMessage(Exception):
    """Raise from handler to reject the message."""

    def __init__(self, requeue: bool = False) -> None:
        super().__init__()
        self.requeue = requeue