Reference

Transport

class mersal.rabbitmq.transport.QueueDeclarationOptions

Bases: object

QueueDeclarationOptions(durable: ‘bool’, exclusive: ‘bool’, arguments: ‘pamqp_common.Arguments’, auto_delete: ‘bool’)

__init__(durable: bool, exclusive: bool, arguments: pamqp_common.Arguments, auto_delete: bool) → None
class mersal.rabbitmq.transport.RabbitMqTransport

Bases: BaseTransport

A RabbitMQ transport backed by a single persistent, auto-recovering connection.

Topology:

Two durable exchanges are declared: a direct exchange used for point-to-point sends (each app’s input queue is bound to it with a routing key equal to its own address), and a topic exchange used for pub/sub (see mersal.rabbitmq.subscription_storage.RabbitMqSubscriptionStorage).

Backend:

Anyio-native, including the consumer pump: _pump runs in a long-lived task group (_StartedState.pump_task_group) that outlives any single receive call, with a per-consumer anyio.CancelScope (see _Consumer) used to cancel just one consumer’s pump - e.g. on self-heal - without tearing down the group itself. send_outgoing_messages fires concurrent publishes via an anyio task group too.

Connections and channels:

A single aio_pika.connect_robust connection is opened once and reused for the lifetime of the transport; aio_pika’s robust connection/channel classes transparently redeclare topology and resume consuming after a dropped connection, so we don’t hand-roll reconnection logic. Two long-lived channels are kept open on top of it - one dedicated to publishing (with publisher confirms enabled, so send only returns once the broker has actually accepted the message) and one dedicated to consuming (with a QoS prefetch limit) - so a failure on one side can’t take down the other.

Startup:

Connecting is lazy: the first call to send, receive, or create_queue establishes the connection and topology if it hasn’t happened yet. __call__ (registered as an on-startup lifespan hook by RabbitMQPlugin) simply triggers this eagerly, so the cost of connecting is paid at app startup rather than on the first message - but nothing breaks if __call__ is never invoked. After close, the next use starts the transport again from scratch.

Self-healing:

A dead consumer (e.g. its channel closed and wasn’t - or couldn’t be - transparently recovered) is noticed reactively, the next time receive is called. A vanished queue (e.g. deleted by a TTL/x-expires policy) is noticed proactively instead, by a periodic passive-existence check - see RabbitMqTransportConfig.passive_queue_check_interval. Recreating a vanished queue only restores its direct-exchange binding; the queue_recreated_hook property lets a subscription storage re-establish topic-exchange bindings too (see RabbitMQPlugin).

Send-only apps:

See RabbitMqTransportConfig.send_only: this app’s own input queue is only ever declared, bound, and consumed from when it isn’t send-only, since a send-only app never receives.

__init__(config: RabbitMqTransportConfig, periodic_task_factory: PeriodicAsyncTaskFactory | None = None, logger: Logger | None = None)
async close() → None

Gracefully tear down the consumer and connection.

Wired up as an on-shutdown lifespan hook by RabbitMQPlugin so the underlying connection isn’t just abandoned when the app stops. The transport can be used again afterwards; the next use starts it from scratch.

async ensure_connection() → AbstractRobustConnection

Return the transport’s underlying connection, connecting first if necessary.

Lets other RabbitMQ-backed components sharing this broker (e.g. RabbitMqSubscriptionStorage) reuse this connection instead of opening one of their own - one fewer TCP connection and reconnect state machine against the broker.

property queue_recreated_hook: Callable[[str], Awaitable[None]] | None

Callback invoked with self.address whenever the passive queue check finds the input queue gone and recreates it.

Recreating the queue only restores its direct-exchange binding (see _declare_and_bind) - any topic-exchange bindings it had (i.e. this app’s subscriptions) are gone with the deleted queue. RabbitMQPlugin wires this to RabbitMqSubscriptionStorage.rebind_subscriptions so those get re-established too.

async receive(transaction_context: TransactionContext) → TransportMessage | None

Return the next message, or None after receive_timeout seconds without one.

The bounded wait is purely local - the pump keeps the AMQP consumer running regardless, so timing out touches neither the broker nor the consumer, and a message arriving just after the deadline is simply picked up by the next call.

property supports_deferral: bool

Whether the transport honors the deferred_until header by holding the message back until it’s due.

class mersal.rabbitmq.transport.RabbitMqTransportConfig

Bases: object

RabbitMqTransportConfig(connection_uri: ‘str’, input_queue_name: ‘str’, send_only: ‘bool’ = False, should_declare_exchanges: ‘bool’ = True, should_declare_input_queue: ‘bool’ = True, should_bind_input_queue: ‘bool’ = True, direct_exchange_arguments: ‘pamqp_common.Arguments | None’ = None, topic_exchange_arguments: ‘pamqp_common.Arguments | None’ = None, direct_exchange_name: ‘str’ = ‘mersal.direct’, topic_exchange_name: ‘str’ = ‘mersal.topics’, delayed_exchange_name: ‘str | None’ = None, input_queue_declaration_options: ‘QueueDeclarationOptions | None’ = None, default_queue_declaration_options: ‘QueueDeclarationOptions | None’ = None, prefetch_count: ‘int’ = 50, passive_queue_check_interval: ‘float | None’ = 60.0, receive_timeout: ‘float’ = 5.0)

__init__(connection_uri: str, input_queue_name: str, send_only: bool = False, should_declare_exchanges: bool = True, should_declare_input_queue: bool = True, should_bind_input_queue: bool = True, direct_exchange_arguments: pamqp_common.Arguments | None = None, topic_exchange_arguments: pamqp_common.Arguments | None = None, direct_exchange_name: str = 'mersal.direct', topic_exchange_name: str = 'mersal.topics', delayed_exchange_name: str | None = None, input_queue_declaration_options: QueueDeclarationOptions | None = None, default_queue_declaration_options: QueueDeclarationOptions | None = None, prefetch_count: int = 50, passive_queue_check_interval: float | None = 60.0, receive_timeout: float = 5.0) → None
delayed_exchange_name: str | None = None

Name of the exchange used for deferred messages (e.g. "mersal.delayed").

Setting it enables native deferral (Mersal.defer/defer_local) through the rabbitmq_delayed_message_exchange broker plugin, which must be enabled on the broker. The exchange is declared (when should_declare_exchanges) as an x-delayed-message exchange bound to the direct exchange, so a deferred message is routed exactly like a plain send once its delay has elapsed. Use a dedicated delayed exchange per direct exchange: every direct exchange bound to it gets every deferred message.

Without it, deferred messages are sent as they are - to a timeout manager (see mersal.timeouts.TimeoutsConfig), which holds them until due.

passive_queue_check_interval: float | None = 60.0

How often, in seconds, to passively verify the input queue still exists on the broker (e.g. it wasn’t deleted by a TTL/x-expires policy) and proactively recreate it if not.

This exists on top of the reactive self-heal in receive (which only notices a dead consumer, not a vanished queue) because a queue nobody is currently consuming from or publishing to wouldn’t otherwise be noticed missing until something tried to use it again. Set to None to disable the check entirely.

prefetch_count: int = 50

Maximum number of unacked messages the broker will push to this transport’s consumer at once. Sized a few times larger than the app’s expected processing concurrency (see max_parallelism on the worker) keeps the pipeline fed without letting one slow consumer hoard the whole queue.

Also size this against processing time, not just parallelism: RabbitMQ (3.8.15+) forcibly closes a channel whose oldest unacked delivery exceeds consumer_timeout (broker-side setting, default 30 minutes) - and a message can sit unacked in _Consumer.receive_stream (this transport’s local prefetch buffer, ahead of the app actually processing it) for a while under a large prefetch_count and slow handlers. Hitting the timeout kills the consume channel; the transport self-heals it (see receive), but every message still in flight at that point gets redelivered.

receive_timeout: float = 5.0

Maximum seconds receive waits for a message before returning None.

Transport.receive must return within a bounded time rather than blocking forever, so the worker’s heartbeat keeps advancing while idle - an unbounded wait here would make a merely-idle transport indistinguishable from a wedged one to the liveness watcher. Idle backoff between calls is the worker’s job, not this transport’s.

send_only: bool = False

Set by RabbitMQPlugin from the owning app’s send_only configuration - a send-only app never receives, so this transport skips declaring/binding its own input queue and never opens a consume channel or consumer for it.

Subscription storage

class mersal.rabbitmq.subscription_storage.RabbitMqSubscriptionStorage

Bases: SubscriptionStorage

A SubscriptionStorage that stores subscriptions as native RabbitMQ topic-exchange bindings.

__init__(config: RabbitMqSubscriptionStorageConfig, connection_provider: Callable[[], Awaitable[aio_pika.abc.AbstractRobustConnection]] | None = None) → None
Parameters:
  • config – Connection and topology settings.

  • connection_provider – If given, called to obtain the connection instead of opening one of its own - lets this storage share a connection with a RabbitMqTransport on the same broker (RabbitMQPlugin wires this up using the transport’s ensure_connection). Since the provider’s owner is responsible for the connection’s lifetime, close becomes a no-op.

async get_subscriber_addresses(topic: str) → set[str]

Get addresses subscribed for the given topic.

Parameters:

topic – topic name to get the addresses for.

Returns:

A set of addresses subscribed to this topic.

property is_centralized: bool

Whether this storage is centralized.

Centralized storage means topic subscriptions are stored in one place and registration/unregistration can be done by directly calling register_subscriber and unregister_subscriber, respectively.

Non centralized means each topic handles its own storage and registration/unregistration is performed by sending a message to the topic owner (async).

async register_subscriber(topic: str, subscriber_address: str) → None

Bind subscriber_address’s queue to topic on the topic exchange.

The queue itself is never declared here - it’s expected to already exist, declared once by its owning RabbitMqTransport at that app’s own startup (subscriber_address is that transport’s own address). Declaring it a second place would need every declaration option kept in sync with the transport’s or risk a channel-closing PRECONDITION_FAILED on mismatch.

async unregister_subscriber(topic: str, subscriber_address: str) → None

Unregister the given address for the given topic.

class mersal.rabbitmq.subscription_storage.RabbitMqSubscriptionStorageConfig

Bases: object

RabbitMqSubscriptionStorageConfig(connection_uri: ‘str’, topic_exchange_name: ‘str’ = ‘mersal.topics’, should_declare_topic_exchange: ‘bool’ = True, topic_exchange_arguments: ‘pamqp_common.Arguments | None’ = None)

__init__(connection_uri: str, topic_exchange_name: str = 'mersal.topics', should_declare_topic_exchange: bool = True, topic_exchange_arguments: pamqp_common.Arguments | None = None) → None
topic_exchange_name: str = 'mersal.topics'

Must match the topic_exchange_name of the RabbitMqTransport instances sharing this broker - subscribing and publishing only agree on where events land if both sides bind to and publish through the same exchange.

Plugin

class mersal.rabbitmq.plugin.RabbitMQPlugin

Bases: Plugin

__init__(config: RabbitMQPluginConfig) → None
class mersal.rabbitmq.plugin.RabbitMQPluginConfig

Bases: object

RabbitMQPluginConfig(connection_uri: ‘str’, input_queue_name: ‘str’, should_declare_exchanges: ‘bool’ = True, should_declare_input_queue: ‘bool’ = True, should_bind_input_queue: ‘bool’ = True, direct_exchange_arguments: ‘pamqp_common.Arguments | None’ = None, topic_exchange_arguments: ‘pamqp_common.Arguments | None’ = None, direct_exchange_name: ‘str’ = ‘mersal.direct’, topic_exchange_name: ‘str’ = ‘mersal.topics’, delayed_exchange_name: ‘str | None’ = None, input_queue_declaration_options: ‘QueueDeclarationOptions | None’ = None, default_queue_declaration_options: ‘QueueDeclarationOptions | None’ = None, prefetch_count: ‘int’ = 50, passive_queue_check_interval: ‘float | None’ = 60.0)

__init__(connection_uri: str, input_queue_name: str, should_declare_exchanges: bool = True, should_declare_input_queue: bool = True, should_bind_input_queue: bool = True, direct_exchange_arguments: pamqp_common.Arguments | None = None, topic_exchange_arguments: pamqp_common.Arguments | None = None, direct_exchange_name: str = 'mersal.direct', topic_exchange_name: str = 'mersal.topics', delayed_exchange_name: str | None = None, input_queue_declaration_options: QueueDeclarationOptions | None = None, default_queue_declaration_options: QueueDeclarationOptions | None = None, prefetch_count: int = 50, passive_queue_check_interval: float | None = 60.0) → None
delayed_exchange_name: str | None = None

Enables deferral through the broker’s delayed message exchange plugin - see RabbitMqTransportConfig.delayed_exchange_name.

passive_queue_check_interval: float | None = 60.0

How often, in seconds, to passively verify the input queue still exists on the broker (e.g. it wasn’t deleted by a TTL/x-expires policy) and proactively recreate it if not.

This exists on top of the reactive self-heal in receive (which only notices a dead consumer, not a vanished queue) because a queue nobody is currently consuming from or publishing to wouldn’t otherwise be noticed missing until something tried to use it again. Set to None to disable the check entirely.

prefetch_count: int = 50

Maximum number of unacked messages the broker will push to this transport’s consumer at once. Sized a few times larger than the app’s expected processing concurrency (see max_parallelism on the worker) keeps the pipeline fed without letting one slow consumer hoard the whole queue.