Skip to content

xtr_messenger

A message bus built from envelopes, stamps and a middleware chain.

Dispatch wraps a message in an :class:Envelope and walks it through a middleware chain. MiddlewareInterface records what it did by appending a :class:StampInterface; routing sends the envelope to one or more named transports.

A message crossing a transport is written and read back with xtr-serializer, so it arrives exactly as it left. A transport that needs a broker library is a package of its own, found by its DSN scheme once installed — RabbitMQ is xtr-amqp-messenger, the amqp extra.

Dsn dataclass

Dsn(raw: str, scheme: str, connection: str, options: Mapping[str, str])

A parsed transport DSN.

Attributes:

  • raw (str) –

    The DSN as written, which adapters pass to their own client.

  • scheme (str) –

    What a factory dispatches on, lowercased.

  • connection (str) –

    The DSN without its options, still a usable DSN. Two transports that differ only in their query string address the same server, so this is what decides whether they can share a connection.

  • options (Mapping[str, str]) –

    Decoded query-string parameters.

parse classmethod

parse(raw: str) -> Dsn

Read raw into its scheme, connection and options.

Raises:

  • InvalidDsnError –

    If raw carries no scheme, cannot be split into a URL at all, or carries an @ beyond its authority — the mark of credentials with an unescaped ? or #, which would silently move part of the password into the options. Userinfo must be percent-encoded.

InvalidDsnError

InvalidDsnError(dsn: str, reason: str | None = None)

Bases: MessageBusError

A DSN that cannot be read into a transport selection.

The message shows the DSN redacted, never as written — an invalid DSN is exactly the kind whose credentials end up somewhere unexpected.

Record the DSN that could not be read, and why.

Without reason, the DSN is missing the scheme that selects its transport — the commonest way one goes wrong.

Envelope dataclass

Envelope(message: object, stamps: tuple[StampInterface, ...] = ())

A dispatched message wrapped with an ordered tuple of stamps.

The envelope is immutable: every mutator returns a new instance, so a middleware can hand the same envelope down the chain while publishing its own stamped variant upstream, and two senders in a fan-out never observe each other's stamps.

Attributes:

  • message (object) –

    The payload being dispatched. The bus never inspects it.

  • stamps (tuple[StampInterface, ...]) –

    Stamps appended by the middleware traversed so far, in order.

wrap classmethod

wrap(message: object, stamps: Iterable[StampInterface] = ()) -> Envelope

Return message as an envelope, passing an existing one through.

An already-wrapped envelope keeps its stamps and gains stamps, which is what makes re-dispatching a stamped envelope meaningful.

with_stamps

with_stamps(*stamps: StampInterface) -> Envelope

Return a copy of this envelope with stamps appended.

without_stamps

without_stamps(stamp_type: type[StampInterface]) -> Envelope

Return a copy with every stamp_type stamp removed.

Subclasses are removed too, which is how a serializer drops the whole :class:~xtr_messenger.stamp.NonSendableStampInterface family in one call.

all

all(stamp_type: type[StampT]) -> tuple[StampT, ...]

Return every stamp of stamp_type, in the order they were added.

last

last(stamp_type: type[StampT]) -> StampT | None

Return the most recently added stamp_type stamp, or None.

When a stamp type can be added more than once, the last one wins.

DelayedMessageHandlingError

DelayedMessageHandlingError(envelope: Envelope, failures: Sequence[tuple[Envelope, Exception]])

Bases: MessageBusError

One or more messages held back with a DispatchAfterCurrentBusStamp failed.

The message being handled succeeded — what it did stands — and then the messages its handling held back were dispatched, each in turn, every one tried even when an earlier one failed. The first failure is the cause.

Attributes:

  • envelope (Envelope) –

    The message whose handling held them back, as its handling left it.

  • failures (tuple[tuple[Envelope, Exception], ...]) –

    Each held-back message that failed, with what its dispatch raised, in the order dispatched.

  • errors (tuple[Exception, ...]) –

    What each failed dispatch raised, in the same order.

Record the message that succeeded and each held-back message that then failed.

HandlersFailedError

HandlersFailedError(envelope: Envelope, errors: Mapping[str, Exception])

Bases: MessageBusError

One or more handlers of a message raised, after every handler had its turn.

One failing handler does not keep the others from running: each is independent, and an unrelated one — an audit trail, a metric — must not go quiet because another broke. What every handler that failed raised is kept, by handler name, and the first of them is the cause.

Attributes:

  • envelope (Envelope) –

    The message as handling left it, with a :class:~xtr_messenger.stamp.HandledStamp for every handler that succeeded.

  • errors (Mapping[str, Exception]) –

    What each failed handler raised, by handler name, in the order the handlers ran; a name another failed handler already took is told apart as name#2, name#3….

Record the envelope handling left and what each failed handler raised.

HandlerSignatureError

HandlerSignatureError(handler_name: str, parameters: tuple[str, ...])

Bases: MessageBusError

A handler's parameters are not a shape the bus can call.

Record the handler and the parameters it declared.

IncompatibleReceiversError

IncompatibleReceiversError(brokered: tuple[str, ...], registered: tuple[str, ...])

Bases: MessageBusError

A transport that brings its own worker was asked to share it with receivers.

A broker that runs its own consume loop — taskiq does — cannot also drive a receiver registered with the application, and the library's own loop cannot drive the broker. Run them as separate workers.

Record the transports with their own worker, and the receivers asked alongside.

InvalidMiddlewareArgumentsError

InvalidMiddlewareArgumentsError(name: str, reason: str)

Bases: MessageBusError

The configuration gives middleware arguments it does not take.

A configuration entry {name: {argument: value}} naming an argument the middleware's builder does not take, or written in another shape, is refused. With a container, an argument naming no constructor parameter fails the build like any definition argument.

Attributes:

  • name (str) –

    The middleware the arguments were for.

  • reason (str) –

    What is wrong with them.

Record which middleware was misconfigured, and how.

InvalidTransportOptionError

InvalidTransportOptionError(option: str, value: str, expected: str)

Bases: MessageBusError

A transport setting holds a value its adapter cannot use.

The setting may have come from the DSN's query string or from options — both reach an adapter the same way, so neither is named.

Record the setting, the value it held, and what it should hold.

MessageBusError

Bases: Exception

Base class for every error raised by this library.

Catch this to handle anything the bus can go wrong with; catch a subclass to handle one cause. Every subclass carries the data a caller needs as typed attributes and composes its own message from them.

MessageDecodingFailedError

MessageDecodingFailedError(reason: str, message_name: str | None = None)

Bases: MessageBusError

An encoded envelope could not be turned back into a typed message.

Deliberately loud: a silently mis-decoded payload reaches the handler as the wrong shape and fails far from its cause.

Record why decoding failed, and for which message when known.

MessageEncodingFailedError

MessageEncodingFailedError(reason: str, message_name: str)

Bases: MessageBusError

A message could not be turned into something a transport can carry.

Raised on the producer's side, before anything is sent — a message or a stamp holding a value the serializer cannot write, or would not read back exactly.

Record why encoding failed, and for which message.

MissingSerializerError

MissingSerializerError(scheme: str, reason: str)

Bases: MessageBusError

A transport has to write its messages, and was given nothing to write them with.

Raised where the transport is built, never when the application boots: a process speaking only sync:// has no messages to write and needs no serializer, so its absence only matters once a transport would use it.

Record which scheme needed the serializer, and where to give it one.

MixedDsnError

MixedDsnError(dsns: tuple[str, ...])

Bases: MessageBusError

A worker was asked to serve transports that live on different brokers.

Record the conflicting DSNs, redacted — an attribute leaks as easily as a message.

NoFailureTransportError

NoFailureTransportError(known: tuple[str, ...])

Bases: MessageBusError

No failure transport was named, and the configuration has no default one.

Record the failure transports there are to choose from.

NoHandlerForMessageError

NoHandlerForMessageError(message_type: type, handled_types: tuple[str, ...])

Bases: MessageBusError

No handler is registered for a message that reached handling.

In a worker this almost always means the module declaring the handler was never imported, so the registration decorator never ran. Failing is the safe reading: the alternative is acknowledging the message and losing it silently.

Record the unhandled type alongside the types that do have handlers.

NoSenderForMessageError

NoSenderForMessageError(message_type: type, routed_types: tuple[str, ...])

Bases: MessageBusError

No transport is routed for a dispatched message type.

Raised before any transport is touched, so nothing was enqueued when it surfaces.

Record the unrouted type alongside the types that are routed.

NotConsumableError

NotConsumableError(names: tuple[str, ...], scheme: str)

Bases: MessageBusError

A transport sends but cannot be consumed, and brings no worker either.

Reaching this means an adapter implements only the sending half and does not implement :class:~xtr_messenger.worker_providing_interface.WorkerProvidingInterface, so there is nothing to run and no way to build it.

Record which transports were asked for, and their scheme.

UnknownMessageNameError

UnknownMessageNameError(name: str)

Bases: MessageBusError

A wire message name could not be resolved back to a Python type.

Record the unresolvable name.

UnknownMiddlewareError

UnknownMiddlewareError(name: str, known: tuple[str, ...])

Bases: MessageBusError

The configuration names middleware this process has nothing registered for.

Record what was named, and what a name may actually be.

UnknownTransportError

UnknownTransportError(names: tuple[str, ...], known: tuple[str, ...])

Bases: MessageBusError

A route or a worker names a transport the configuration does not define.

Record what was asked for, and what is actually configured.

UnknownTransportOptionError

UnknownTransportOptionError(scheme: str, unknown: tuple[str, ...], known: tuple[str, ...])

Bases: MessageBusError

A transport DSN carries an option its adapter does not recognise.

Raised rather than ignored because an unrecognised option is always a mistake in configuration someone wrote by hand — a typo, or a setting meant for a different scheme. Dropping it silently leaves the transport running on defaults that nobody chose, which is the failure this exists to prevent.

Record the scheme, what it did not recognise, and what it accepts.

UnsupportedStampError

UnsupportedStampError(stamp_name: str, transport: str)

Bases: MessageBusError

A transport was handed a stamp it cannot act on.

A stamp a transport ignores is a silent failure: the caller asked for behaviour — a delay, say — and the message went out immediately with no sign the request was dropped. Raising names the stamp and the transport so the mismatch surfaces where it is made, not as a message that never behaved as asked.

Record which stamp could not be honoured, and by which transport.

UnsupportedTransportOperationError

UnsupportedTransportOperationError(transport: str, operation: str)

Bases: MessageBusError

A transport cannot list, count, find or receive, and was asked to.

What a transport can do beyond sending is what it implements: listing and finding messages is :class:~xtr_messenger.transport.receiver.ListableReceiverInterface, receiving is :class:~xtr_messenger.transport.receiver.ReceiverInterface.

Record the transport and what it was asked to do — "list messages", say.

FailedMessageFilter dataclass

FailedMessageFilter(class_name: str | None = None, failed_after: datetime | None = None, failed_before: datetime | None = None)

Selects failed messages by class name and by the time they failed.

Both bounds of the time window are inclusive. The time a message failed is the one its :class:~xtr_messenger.stamp.SentToFailureTransportStamp records, so a message carrying none is never selected by a time window.

Attributes:

  • class_name (str | None) –

    The dotted name of the message's class — module.QualName — to select only those.

  • failed_after (datetime | None) –

    Select only messages that failed at or after this.

  • failed_before (datetime | None) –

    Select only messages that failed at or before this.

is_empty

is_empty() -> bool

Tell whether this selects every message.

matches

matches(envelope: Envelope) -> bool

Tell whether envelope is one this selects.

select async

select(receiver: ListableReceiverInterface, limit: int | None = None) -> AsyncIterator[Envelope]

Yield what receiver keeps that this selects, limit of them at most.

The limit bounds what is selected: when this selects some messages only, every one is read until that many match.

FailedMessageRepository

FailedMessageRepository(transports: TransportLocator, bus: MessageBusInterface, transport_names: Sequence[str], global_transport_name: str | None = None)

Reads and removes the messages kept in the failure transports.

What the messenger:failed:* commands are built on, so listing, inspecting, removing and dispatching again a failed message can be done from outside the console too.

Every method takes the failure transport to read by name; left out, it is the configuration's own failure_transport.

Read the failure transports transport_names out of transports.

Parameters:

  • transports (TransportLocator) –

    Where each transport is reached by name.

  • bus (MessageBusInterface) –

    What :meth:redispatch dispatches a message again through.

  • transport_names (Sequence[str]) –

    The transports that are failure transports.

  • global_transport_name (str | None, default: None ) –

    The one read when none is named.

transport_names property

transport_names: tuple[str, ...]

Return every failure transport, the configuration's own first.

global_transport_name property

global_transport_name: str | None

Return the failure transport read when none is named, if there is one.

message_id staticmethod

message_id(envelope: Envelope) -> str | None

Return the id envelope is kept under in its transport, if it carries one.

prepare_for_redispatch staticmethod

prepare_for_redispatch(envelope: Envelope) -> Envelope

Return envelope without what must not travel with it when dispatched again.

What only meant something where it was kept goes — what this process stamped on it, the id it was kept under — and so does the mark of its failure: dispatched again, it is a message like any other.

supports_listing

supports_listing(transport: str | None = None) -> bool

Tell whether the failure transport can list and find its messages.

Raises:

count async

count(transport: str | None = None) -> int | None

Return how many messages the failure transport keeps, or None if it cannot count.

Raises:

find async

find(message_id: str, transport: str | None = None) -> Envelope | None

Return the failed message kept as message_id, or None when there is none.

Raises:

all

all(transport: str | None = None, selected: FailedMessageFilter | None = None, limit: int | None = None) -> AsyncIterator[Envelope]

Yield the failed messages selected selects, limit of them at most.

The failure transport is resolved now, so one that cannot be read is reported by this call rather than by the first step of what it returns.

Raises:

remove async

remove(envelope: Envelope, transport: str | None = None) -> None

Drop envelope from the failure transport for good.

By acknowledging it: rejecting it would hand it back to the transport's own retries, which is what retrying it does.

Raises:

redispatch async

redispatch(envelope: Envelope, transport: str | None = None) -> None

Dispatch envelope again, then drop it from the failure transport.

Dropped only once dispatched: a dispatch that raises leaves it where it is, to be dispatched once what failed is fixed.

Raises:

  • MessageBusError –

    Whatever dispatching raises, or what :meth:remove does.

receiver

receiver(transport: str | None = None) -> ReceiverInterface

Return the failure transport as the receiver it must be to be read.

Raises:

HandlerDescriptor dataclass

HandlerDescriptor(handler: Handler | type, name: str, wants_envelope: bool, call: Handler)

A registered handler, and how to call it.

handler is what was declared: a function, a callable object, or a class whose instances are callable — built once, when its first message arrives, and shared by every message after. call is what runs. The two start out as the same thing, and an integration that has to wrap a handler (a container filling its parameters, a span, a timer) replaces call while handler keeps saying what was declared.

of classmethod

of(handler: Handler | type, name: str | None = None) -> HandlerDescriptor

Describe handler by inspecting the signature it declares.

The bus calls a handler with the message, and with the envelope too when a second parameter is annotated :class:Envelope. Parameters a dependency-injection container fills — xtr-dependency-injection's Injected[T] — may follow; they are the container's to supply, not the bus's.

Raises:

invoke async

invoke(envelope: Envelope) -> object

Call the handler with the message, and the envelope if it asked.

Returns:

  • object –

    What the handler returned, which the bus records on the

  • object –

    class:~xtr_messenger.stamp.HandledStamp it leaves behind.

HandlersLocator

HandlersLocator()

Bases: HandlersLocatorInterface

Binds message types to the handlers that consume them.

Lookup walks the message's method resolution order, so registering a base class or a shared marker class handles every subclass — alongside whatever the subclass registers of its own.

Start empty.

register

register(message_type: type, handler: Handler | type, name: str | None = None) -> HandlerDescriptor

Bind handler to message_type and return its descriptor.

Raises:

handlers_for

handlers_for(message_type: type) -> tuple[HandlerDescriptor, ...]

Return every handler bound to message_type or any of its bases.

Most specific first, and a handler registered twice across the chain runs once.

All of them, not the nearest ancestor's. Stopping at the first match meant registering a handler on a subclass silently switched off one registered on its base — an audit trail or a metric attached to a marker class would stop firing the moment someone handled one subclass specifically, with nothing to indicate it. Routing already accumulates the same way, so the two now agree.

message_types

message_types() -> tuple[type, ...]

Return every message type with at least one handler.

decorate

decorate(wrap: Callable[[HandlerDescriptor], HandlerDescriptor]) -> None

Apply wrap to every handler, registered now or later.

For wrapping handlers in something they should not have to know about — a container filling their parameters, a span, a timer. Declaration stays where it is; this changes what is called.

Decorators apply in the order given, always to the handler as it was declared. One equal to a decorator already applied takes its place rather than stacking on it, which is how an integration rebinds every handler — to a new container, say — without the old binding lingering underneath.

HandlersLocatorInterface

Bases: Protocol

Binds message types to the handlers that consume them.

Both halves are here on purpose. Declaring a handler writes to a registry and consuming a message reads from one, but they are the same registry — splitting the contract would mean an application that supplies its own could satisfy only half of what the library does with it.

register

register(message_type: type, handler: Handler | type, name: str | None = None) -> HandlerDescriptor

Bind handler to message_type and return its descriptor.

handlers_for

handlers_for(message_type: type) -> tuple[HandlerDescriptor, ...]

Return the handlers bound to message_type or any of its bases.

message_types

message_types() -> tuple[type, ...]

Return every message type with at least one handler.

RedispatchMessage dataclass

RedispatchMessage(envelope: object, transport_names: str | tuple[str, ...] | list[str] = ())

Dispatch envelope again, through the routing a publishing bus applies.

Handling this message dispatches the envelope it carries, so whatever produced it — a scheduler generating messages, say — decides only that a message goes out, and routing decides where. transport_names overrides routing for that one dispatch; left empty, the routing table decides, as it would for any dispatch.

It holds an envelope, which no serializer writes, so it lives only in the process that dispatches it: handle it where it is created rather than routing it to a transport.

Carry envelope — or a bare message — and where to send it, if not by routing.

Empty transport names are dropped: "" means no override, not a transport named nothing.

envelope instance-attribute

envelope: object

An :class:~xtr_messenger.Envelope, or a bare message to wrap in one.

message property

message: object

Return the message to be dispatched again, unwrapped from its envelope.

MessageBus

MessageBus(middlewares: Sequence[MiddlewareInterface])

Bases: MessageBusInterface

Dispatches messages through a composed middleware chain.

Snapshot middlewares so later mutation cannot affect a live bus.

dispatch async

dispatch(message: object, *stamps: StampInterface) -> Envelope

Dispatch message through the chain and return the stamped envelope.

A raw message is wrapped in a fresh envelope; an existing envelope is passed through with its stamps intact, so a previously stamped envelope can be re-dispatched.

A fresh cursor is built per call, so the same chain serves any number of dispatches even though each cursor is single-use.

MessageBusConfig dataclass

MessageBusConfig(transports: Mapping[str, TransportConfig] = _no_transports(), routing: Mapping[type | str, str | Sequence[str]] = _no_routes(), middleware: Sequence[str | MiddlewareInterface | Mapping[str, Mapping[str, object]]] = (), default_middleware: bool = True, require_sender: bool = False, handle_unrouted: bool = False, require_handler: bool = True, failure_transport: str | None = None)

The transports that exist, which messages go to them, and the chain.

Attributes:

  • transports (Mapping[str, TransportConfig]) –

    Named transports. A worker selects between these names, so one deployment can run a process per queue instead of one process consuming everything.

  • routing (Mapping[type | str, str | Sequence[str]]) –

    Message type (or "*") to transport name, or several names to fan out. A message may also name its own transport with :func:~xtr_messenger.decorator.as_message; this map wins.

  • middleware (Sequence[str | MiddlewareInterface | Mapping[str, Mapping[str, object]]]) –

    The middleware to run, in order, ahead of routing and handling: a name, middleware already built, or a name with arguments for its constructor — {"audit": {"channel": "billing"}}. "logging" is the name this library ships; a factory's named adds more. An unknown one is refused with :class:~xtr_messenger.exception.UnknownMiddlewareError, and arguments it does not take with :class:~xtr_messenger.exception.InvalidMiddlewareArgumentsError. Middleware keeps no per-message state: one instance serves every dispatch, concurrently, and may serve the bus and the workers alike.

  • default_middleware (bool) –

    Whether routing and handling are appended at all, on the bus and in every worker. False runs only what middleware names, for a chain composed entirely by hand.

  • require_sender (bool) –

    Refuse a message no transport is routed for, rather than letting the dispatch pass quietly.

  • handle_unrouted (bool) –

    Handle a message routed nowhere in this process, rather than letting the dispatch pass quietly.

  • require_handler (bool) –

    Refuse a message handled here that no handler takes. False for a bus shared by processes that each handle some of its messages.

  • failure_transport (str | None) –

    The transport messages are kept in once they failed for good, for every transport that names none of its own — and the one the messenger:failed:* commands read when told no other. See :attr:TransportConfig.failure_transport.

failure_transport_names

failure_transport_names() -> tuple[str, ...]

Return every failure transport: the configuration's own first, then each transport's.

failure_transport_of

failure_transport_of(name: str) -> str | None

Return where the transport name keeps what failed for good, if anywhere.

None too for a transport that is its own failure transport: what fails there for good has nowhere left to go.

by_connection

by_connection() -> dict[str, dict[str, TransportConfig]]

Group the transports by the server each one addresses.

Transports differing only in their query string share a server, and therefore share one connection — which is what lets an adapter open a single broker and hand it to every queue named on it.

MessageBusFactory

MessageBusFactory(config: MessageBusConfig, factories: Sequence[TransportFactoryInterface] | None = None, handlers: HandlersLocatorInterface | None = None, *, logger: LoggerInterface | None = None, named: Mapping[str, MiddlewareBuilder] | None = None)

Builds the bus a publishing process dispatches through.

Pass factories to control how transports are constructed — a serializer of your own, or a scheme the library does not ship.

Build from config; factories overrides lazy discovery.

handlers replaces the process-wide registry for everything this bus handles, sync:// included: no transport calls a handler itself, they all hand the message back to the bus.

logger is what the "logging" middleware writes through when the configuration names it. named adds names of your own for the configuration to use, each mapped to what builds it.

bus

bus() -> MessageBus

Build a bus that routes according to the configuration.

What the configuration's middleware names runs first; routing goes after it, because nothing should come between routing and the transport.

Handling always comes after routing, which is the order that lets one composition serve both sides: a message being published is routed and stops there, while one that arrived from a transport — or was handed straight back by sync:// — carries a :class:~xtr_messenger.stamp.ReceivedStamp, is deliberately not routed again, and falls through to be handled here.

default_middleware=False in the configuration leaves routing and handling off altogether, for a bus composed entirely by hand.

Raises:

MessageBusInterface

Bases: Protocol

The port publishers depend on.

Call sites type against this instead of :class:~xtr_messenger.message_bus.MessageBus so the middleware composition and the transports behind it stay an infrastructure concern.

dispatch async

dispatch(message: object, *stamps: StampInterface) -> Envelope

Dispatch message and return the envelope the chain hands back.

DispatchAfterCurrentBusMiddleware

Bases: MiddlewareInterface

Dispatches messages stamped DispatchAfterCurrentBusStamp once the current one succeeded.

The first message dispatched in a context is the current one: the stamped messages dispatched while it is handled are held back — the rest of their chain kept — and dispatched, in order, once its whole chain returned. If it raised, they are dropped. A stamped message dispatched with nothing being handled goes out at once.

The chain puts it first, ahead of every configured middleware, so what those do around the current message — commit a transaction — is done before anything held back goes out.

handle async

handle(envelope: Envelope, stack: StackInterface) -> Envelope

Hold envelope back, pass it on, or handle it as the current message.

Raises:

HandleMessageMiddleware

HandleMessageMiddleware(registry: HandlersLocatorInterface | None = None, *, require_handler: bool = True)

Bases: MiddlewareInterface

Runs every handler bound to the message, stamping each one.

This is the end of the line for a message that stays in this process. Put it last: :class:SendMessageMiddleware short-circuits when a message was routed to a transport, so anything reaching here was either not routed anywhere or arrived from a transport and is meant to be handled now.

That pairing is what makes one bus serve both sides. The publishing process routes and stops; the worker receives, finds a :class:~xtr_messenger.stamp.ReceivedStamp that keeps the message from being published again, falls through, and handles it here.

A message with no handler raises by default rather than passing quietly, because in a worker the overwhelmingly likely cause is an unimported handler module — and the quiet alternative is acknowledging the message and losing the work. Pass require_handler=False where a message genuinely may go unhandled, such as a bus shared by processes that subscribe to different subsets.

Resolve handlers from registry, defaulting to the process-wide one.

handle async

handle(envelope: Envelope, stack: StackInterface) -> Envelope

Invoke each bound handler, then continue down the chain.

Every handler runs, whichever of them raise: they are independent, and one failing must not silence the others.

Raises:

LoggingMiddleware

LoggingMiddleware(logger: LoggerInterface | None = None)

Bases: MiddlewareInterface

Logs the outcome of each dispatch, after the rest of the chain ran.

Placed first so it observes the fully stamped result. It never catches exceptions and never logs errors — the layer that raised owns reporting its own failure, and a swallowed exception here would hide it.

What it writes is graded by severity, so a console command turns -v into how much of a dispatch it sees — xtr-logging's ConsoleHandler prints notices at -v, info at -vv and everything at -vvv:

=============== ====== ========================================= Level Shown Records =============== ====== ========================================= NOTICE -v One per dispatch: the message type, the transport it went to and the id the broker gave it. INFO -vv One per handler that ran, and what it returned. DEBUG -vvv One per dispatch, carrying every stamp the envelope came back with. =============== ====== =========================================

Nothing appears at normal verbosity: a dispatch is routine, and a bus running thousands a second should not say so unasked. Each tier is a distinct record adding what the one above it left out, never a repeat of it, and every value travels as context so a formatter renders it apart from the text.

Log through logger, discarding records without one.

handle async

handle(envelope: Envelope, stack: StackInterface) -> Envelope

Await the chain, record what happened, return the result untouched.

MiddlewareInterface

Bases: Protocol

One link in the dispatch chain.

handle async

handle(envelope: Envelope, stack: StackInterface) -> Envelope

Process envelope and return what to hand back upstream.

Continue the chain with await stack.next().handle(envelope, stack) and return its (optionally re-stamped) result. Return an envelope without calling stack.next() to short-circuit — everything downstream is then skipped. Raising propagates untouched.

Arguments are passed positionally, so an implementation may name its parameters whatever reads best.

SendMessageMiddleware

SendMessageMiddleware(locator: SendersLocatorInterface, *, require_sender: bool = False, handle_unrouted: bool = False)

Bases: MiddlewareInterface

Sends an envelope to every transport it is routed to.

Two rules carry the whole producer/consumer split:

  • An envelope carrying a :class:~xtr_messenger.stamp.ReceivedStamp came from a transport, so it is never routed again — otherwise a consumer would re-publish everything it consumes.
  • Once at least one sender accepted the envelope, the chain short-circuits. A message with a transport configured is handed off, not also handled in the dispatching process — unless a sender hands it back received, as sync:// does, meaning "handle it here": then it continues down the chain to be handled like anything a worker receives.

When nothing is routed the chain stops there, as it does on a bus the factory builds. Set handle_unrouted=True to continue instead, which lets a downstream handling middleware pick the message up in-process.

Each sender of a fan-out is handed the envelope as it was before any of them, plus its own :class:~xtr_messenger.stamp.SentStamp: none sees what another added. What each added is on the envelope returned.

Wire the locator, optionally failing dispatches that route nowhere.

handle async

handle(envelope: Envelope, stack: StackInterface) -> Envelope

Route and send, or fall through when the envelope is not routed.

StackInterface

Bases: Protocol

A cursor over the middleware remaining for one dispatch.

next

next() -> MiddlewareInterface

Return the next middleware, or an identity tail once exhausted.

StackMiddleware

StackMiddleware(middlewares: Sequence[MiddlewareInterface])

Bases: MiddlewareInterface

A single-use cursor that is also its own end-of-chain sentinel.

Walking past the last middleware returns self, whose handle is the identity function. A middleware at the end of the chain can therefore delegate unconditionally instead of special-casing the tail, and an empty chain is a legal no-op dispatch rather than an error.

Start a cursor positioned before the first middleware.

next

next() -> MiddlewareInterface

Advance the cursor, returning the identity tail when exhausted.

handle async

handle(envelope: Envelope, _stack: StackInterface) -> Envelope

Return envelope unchanged — the tail of the chain.

PublisherClosingInterface

Bases: Protocol

A transport factory that has connections of its own to release.

Most transports hold nothing: a sync:// send is a function call, and an in-memory:// one appends to a list. A broker is different — a producer has to open a connection before its first publish, and nothing closes it afterwards, because the consuming side's run loop is what normally does that and a publisher has no loop.

Implement this in that case only, and close exactly what this factory's senders opened. One process may run several applications, each with its own factory; closing more than your own would drop a connection another is still publishing through.

close_publishers async

close_publishers() -> None

Release every connection this factory's senders opened for publishing.

Called as an application shuts down, and safe to call when nothing was ever published: there is simply nothing to close. A connection reopens on the next publish, so this is not a one-way door.

AckReceiptStamp dataclass

AckReceiptStamp(receipt: int)

Bases: NonSendableStampInterface

Identifies a received message so it can later be acked or rejected.

A receiver mints one of these as it yields an envelope, and keeps the means of acknowledging that message — a broker callback, a delivery tag — on its own side, keyed by this receipt. The envelope carries only the number.

That indirection is deliberate. The acknowledging machinery is a live connection-bound object: it cannot be serialized, and it is meaningless in any other process. Keeping it off the envelope means a received message stays exactly as serializable as a sent one, so the same envelope can be forwarded, retried, or written to a dead-letter queue without the transport's private state leaking with it.

Non-sendable, so it is dropped before encoding: a receipt describes this process's relationship to a message, never the message itself.

DelayStamp dataclass

DelayStamp(delay_ms: int)

Bases: StampInterface

Requests delayed delivery, in milliseconds.

Honoured only by a transport that can hold a message before delivering it. The AMQP transport does, through taskiq's delayed-message exchange. The sync:// and in-memory:// transports cannot — they hand a message on at once — and refuse a delayed envelope with :class:~xtr_messenger.exception.UnsupportedStampError rather than delivering it immediately and dropping the request silently.

DispatchAfterCurrentBusStamp dataclass

DispatchAfterCurrentBusStamp()

Bases: NonSendableStampInterface

Dispatch the message only once the message being handled was handled successfully.

A handler that asks for a follow-up — a mail, an event another process consumes — usually means "once what I did is final". Stamped with this, the follow-up waits until every handler of the current message, and every middleware around them — a database transaction's commit included — has finished; if that fails, it is never dispatched. Dispatched with nothing being handled, it goes out at once.

ErrorDetailsStamp dataclass

ErrorDetailsStamp(exception_class: str, exception_message: str)

Bases: StampInterface

Snapshot of why handling failed.

Carries the exception class name and message as plain strings so the stamp stays serializable and free of live traceback references.

HandledStamp dataclass

HandledStamp(handler_name: str, result: object = None)

Bases: NonSendableStampInterface

Records that a handler ran, and what it returned.

result is the handler's return value as it came back — never sent anywhere, so it need not be serializable. None for a handler that returns nothing.

NonSendableStampInterface dataclass

NonSendableStampInterface()

Bases: StampInterface

Marker for stamps that must never cross a transport boundary.

Serializers drop these before encoding. Use it for markers describing the local process — what received this, what handled it — rather than facts the consumer needs.

ReceivedStamp dataclass

ReceivedStamp(transport_name: str)

Bases: NonSendableStampInterface

Marks an envelope as having arrived from a transport.

Its presence tells :class:~xtr_messenger.middleware.SendMessageMiddleware not to route the message again, which is what stops a consumer from re-publishing everything it consumes.

RedeliveryStamp dataclass

RedeliveryStamp(retry_count: int)

Bases: StampInterface

Records which delivery attempt this is.

retry_count is zero on first delivery and increments per redelivery, so a handler can tell a first attempt from a final one.

SentStamp dataclass

SentStamp(sender_class: str, sender_alias: str)

Bases: NonSendableStampInterface

Records that a sender accepted the envelope.

One stamp per sender the message was routed to, appended by :class:~xtr_messenger.middleware.SendMessageMiddleware.

SentToFailureTransportStamp dataclass

SentToFailureTransportStamp(original_receiver_name: str, failed_at: datetime)

Bases: StampInterface

Where a message failed for good, and when.

Added by the transport that moves a message to its failure transport, so the messenger:failed:* commands can say which transport it failed on and select it by when it failed.

Attributes:

  • original_receiver_name (str) –

    The transport the message failed on.

  • failed_at (datetime) –

    When it was moved to the failure transport, timezone-aware.

StampInterface dataclass

StampInterface()

Marker every stamp implements by inheriting it.

Carries no data of its own — it exists so Envelope.all and Envelope.last can filter by type. Stamps stay frozen: they are value objects exchanged between middleware, and mutability would let one middleware rewrite another's recorded result.

Deliberately a base class rather than a typing.Protocol. A protocol with no members is structurally satisfied by every object — including None and 42 — so isinstance against it is always true, and stripping by stamp family would silently discard every stamp. Inheritance is what makes the check mean something.

TransportMessageIdStamp dataclass

TransportMessageIdStamp(message_id: str)

Bases: StampInterface

The transport-assigned identifier for an enqueued message.

TransportNamesStamp dataclass

TransportNamesStamp(transport_names: tuple[str, ...])

Bases: StampInterface

Overrides routing for one dispatch, bypassing the routing table.

InMemoryTransport

InMemoryTransport(serializer: SerializerInterface | None = None)

Bases: TransportInterface

Captures dispatched envelopes so a test can assert on them.

Pass a serializer to round-trip every envelope through encode/decode on the way in. That costs nothing in a test and catches the class of bug where a message only fails once it meets a real transport — an unserializable field, or a name that will not resolve on the consumer.

Mutable by design: recording is the whole point.

The record and the queue are separate on purpose. :attr:sent is an append-only log that nothing drains, while :meth:get consumes from an independent queue that :meth:send also feeds. Were they one structure, running a worker would empty the very list the test then asserts on, and the assertion would pass or fail depending on scheduling. Keeping them apart means a single test can both drive a real receive loop and check what was published, without the two interfering.

Record into a fresh log, optionally round-tripping through serializer.

sent property

sent: tuple[Envelope, ...]

Return the envelopes recorded so far, in dispatch order.

Never drained by :meth:get, so this stays a complete history even while a worker consumes.

messages property

messages: tuple[object, ...]

Return just the recorded messages, in dispatch order.

rejected property

rejected: tuple[Envelope, ...]

Return the envelopes a consumer rejected, in rejection order.

pending property

pending: int

Return how many envelopes are queued but not yet collected.

clear

clear() -> None

Forget everything recorded, queued, and rejected.

send async

send(envelope: Envelope) -> Envelope

Record envelope, queue it for collection, and stamp a message id.

Raises:

  • UnsupportedStampError –

    If the envelope carries a :class:~xtr_messenger.stamp.DelayStamp: this transport keeps no timer, so a delay cannot be honoured and is refused rather than dropped.

get async

get() -> AsyncIterator[Envelope]

Yield queued envelopes until the queue is empty.

Stops rather than waiting for more, so a test can drive the loop to completion without having to cancel it.

ack async

ack(envelope: Envelope) -> None

Acknowledge envelope; the queue was already drained when it was collected.

reject async

reject(envelope: Envelope) -> None

Record envelope as rejected.

Records the envelope as handed over, not as it was collected, so anything the consumer learned on the way — an :class:~xtr_messenger.stamp.ErrorDetailsStamp saying why — is kept rather than discarded.

InMemoryTransportFactory

InMemoryTransportFactory(serializer: SerializerInterface | None = None)

Bases: TransportFactoryInterface

Builds in-memory:// transports, which record instead of sending.

Transports are built once per name and reused. A recorder is only useful if the code that asserts on it, the code that publishes to it, and any worker that drains it all hold the same object — rebuilding per call would give each of them a private queue and quietly break all three.

Round-trip through serializer when a transport asks to.

Built without one, its transports record what they are handed as it is, and one asking for ?serialize=true is refused.

supports

supports(dsn: Dsn) -> bool

Recognise the in-memory scheme.

create

create(group: Mapping[str, TransportConfig]) -> Mapping[str, SenderInterface]

Return the recorder for each name, building it the first time.

?serialize=true makes a recorder round-trip every message through the serializer, which turns an unserializable field into a test failure rather than a production one.

Raises:

ListableReceiverInterface

Bases: ReceiverInterface, Protocol

A receiver whose messages can be looked into without being handed out.

Every envelope it hands back carries a :class:~xtr_messenger.stamp.TransportMessageIdStamp with the id :meth:find takes, and whatever else :meth:get would stamp it with to settle it — so a listed envelope can be acknowledged or rejected like a received one.

all

all(limit: int | None = None) -> AsyncIterator[Envelope]

Yield the messages waiting in this receiver, limit at most.

find async

find(message_id: str) -> Envelope | None

Return the message kept as message_id, or None when there is none.

MessageCountAwareInterface

Bases: Protocol

A receiver that can tell how many messages wait to be handled.

count async

count() -> int

Return how many messages wait to be handled; on some brokers an approximation.

ReceiverInterface

Bases: Protocol

A transport's receive half: pull messages, then settle them.

Every envelope yielded by :meth:get must eventually be settled exactly once, by :meth:ack when it was handled and :meth:reject when it was not. Until then the broker is entitled to consider it outstanding.

Envelopes arriving here carry a :class:~xtr_messenger.stamp.ReceivedStamp, which stops them being routed back out — a consumer cannot re-publish what it consumes.

:meth:get is an async iterator rather than something a worker polls. That maps onto how brokers actually deliver — they push, and a subscription stays open — so cancelling the task consuming it is a graceful shutdown, and prefetch stays the broker's business rather than something a poll interval has to approximate.

get

get() -> AsyncIterator[Envelope]

Yield envelopes as the transport delivers them.

Yields until cancelled or until the transport is exhausted. Each envelope carries whatever handle the transport needs to settle it later, so it must be passed back to :meth:ack or :meth:reject rather than reconstructed.

A worker that is stopped while waiting cancels the pending step, so cancellation may arrive at any await in here. A message taken from the transport but not yet yielded must not be lost to it: yield without awaiting in between, or hand the message back to the transport — left unacknowledged, on a broker — when cancelled.

ack async

ack(envelope: Envelope) -> None

Tell the transport envelope was handled and may be dropped.

reject async

reject(envelope: Envelope) -> None

Tell the transport envelope failed terminally.

What happens next is the transport's: the worker makes one attempt per message. A transport that keeps a delivery count may put it back for a later attempt — saying so through :class:~xtr_messenger.transport.receiver.RetryingReceiverInterface — and once its attempts run out moves it somewhere it can be inspected, never back in line to fail again at once.

RetryingReceiverInterface

Bases: Protocol

A receiver that puts a rejected message back for another attempt while it has some left.

The worker asks before it announces a failure, so a listener of the failed event — the one paging an administrator, say — can tell an attempt that will be made again from a message that failed for good.

will_retry

will_retry(envelope: Envelope) -> bool

Tell whether rejecting envelope now puts it back for another attempt.

SingleMessageReceiver

SingleMessageReceiver(receiver: ReceiverInterface, envelope: Envelope)

Bases: ReceiverInterface, RetryingReceiverInterface

Yields envelope once, then is exhausted; settles it through receiver.

How one message found in a receiver — by :meth:~xtr_messenger.transport.receiver.ListableReceiverInterface.find, say — is handed to a worker on its own, and settled where it is kept.

Hand out envelope, which receiver holds.

get async

get() -> AsyncIterator[Envelope]

Yield the envelope the first time; nothing after.

ack async

ack(envelope: Envelope) -> None

Acknowledge envelope through the receiver that holds it.

reject async

reject(envelope: Envelope) -> None

Reject envelope through the receiver that holds it.

will_retry

will_retry(envelope: Envelope) -> bool

Tell what the receiver that holds envelope does with it once rejected.

SenderInterface

Bases: Protocol

A transport's send half.

send async

send(envelope: Envelope) -> Envelope

Hand envelope to the transport and return it, possibly re-stamped.

Implementations typically append a :class:~xtr_messenger.stamp.TransportMessageIdStamp.

SendersLocator

SendersLocator(routes: Mapping[type | str, str | Sequence[str]], senders: Mapping[str, SenderInterface])

Bases: SendersLocatorInterface

Maps message types to named transports.

Resolution, most specific first:

  1. A :class:~xtr_messenger.stamp.TransportNamesStamp on the envelope, which overrides everything for that one dispatch.
  2. The table, walking the message's method resolution order — routing a base class or a shared marker class routes every subclass.
  3. The "*" catch-all entry.
  4. The transport declared on the message by :func:~xtr_messenger.decorator.as_message.

The table therefore always wins over what a message declares about itself, so an application can re-route a message it does not own.

Build the table and fail fast on a route naming an unknown transport.

senders_for

senders_for(envelope: Envelope) -> Iterator[tuple[str, SenderInterface]]

Yield the senders this envelope is routed to, without duplicates.

routed_type_names

routed_type_names() -> tuple[str, ...]

Return the routed message types as readable names.

transport_names_for staticmethod

transport_names_for(message_type: type, routes: Mapping[type | str, str | Sequence[str]]) -> tuple[str, ...]

Return the transports routes sends message_type to, by the rules above.

The table walked along the type's method resolution order, then its "*" entry, then what the message declares — everything but a :class:~xtr_messenger.stamp.TransportNamesStamp, which only a dispatch carries. Duplicates are kept, in the order they matched.

SendersLocatorInterface

Bases: Protocol

Resolves which senders an envelope should go to.

senders_for

senders_for(envelope: Envelope) -> Iterator[tuple[str, SenderInterface]]

Yield (transport_name, sender) pairs, most specific first.

routed_type_names

routed_type_names() -> tuple[str, ...]

Return the routed message types, for error messages.

EncodedEnvelope dataclass

EncodedEnvelope(body: str, headers: dict[str, str])

An envelope in transport-ready form.

JsonSerializer

JsonSerializer(serializer: SerializerInterface, stamp_types: Iterable[type[StampInterface]] | None = None)

Bases: SerializerInterface

Encodes messages and their stamps as JSON, exactly.

The body is written by serializer as the message's own class, and read back as the class its type header names, so it arrives as it left: nested dataclasses and models, decimals, enums, a ZonedDateTime, a subclass in a field typed with its base when the base declares a hierarchy. A message that could not make the trip exactly is refused when it is encoded. Every stamp is written the same way, so an application's stamp keeps its values too.

Decoding is an allow-list: the type header resolves only to a declared message, and a stamp header names a class this process must import, so an unrecognised one is dropped rather than resolved. The stamp list defaults to the stamps the library ships plus every stamp declared with :func:~xtr_messenger.decorator.as_stamp — declare a custom stamp, or pass stamp_types, for it to survive the trip.

What arrives is untrusted, so a decoding error says what did not fit and where, never what the data held.

Stamps inheriting :class:~xtr_messenger.stamp.NonSendableStampInterface never leave the process, so they are never written and never restored.

Write bodies and stamps with serializer; restore stamp_types on decode.

Omitting stamp_types restores the stamps the library ships and every stamp declared with :func:~xtr_messenger.decorator.as_stamp — including one declared after this serializer was built. Pass an explicit iterable to restore exactly those, or () to restore none at all.

encode

encode(envelope: Envelope) -> EncodedEnvelope

Render envelope as a JSON body plus type and stamp headers.

Raises:

decode

decode(encoded: EncodedEnvelope) -> Envelope

Rebuild the typed message and its stamps.

Raises:

  • MessageDecodingFailedError –

    If the type header is missing or names no declared message, or the body or a stamp header does not fit its class.

SerializerInterface

Bases: Protocol

Converts envelopes to and from a transport-ready representation.

encode

encode(envelope: Envelope) -> EncodedEnvelope

Render envelope for the wire.

decode

decode(encoded: EncodedEnvelope) -> Envelope

Rebuild an envelope from its wire form.

SetupableTransportInterface

Bases: Protocol

A transport that can create what it needs — a table, a queue — before it is used.

What messenger:setup-transports calls, so a deployment can create everything up front and run with automatic setup off.

setup async

setup() -> None

Create whatever the transport needs that does not exist yet.

SyncTransport

Bases: TransportInterface

Has the message handled immediately, by the bus that dispatched it.

Sending marks the envelope received and hands it straight back, so :class:~xtr_messenger.middleware.SendMessageMiddleware passes it on to the bus's own handling step instead of stopping there. The transport never calls a handler itself, so which handlers run is decided in one place — the bus — whether a message is handled here or by a worker.

Useful for local development and for messages that do not need a worker: the dispatch site keeps the same API, so moving a message onto a real queue later is a routing-table change and nothing else.

Handler exceptions propagate to the dispatcher — there is no queue to retry from, so failing loudly is the honest behaviour.

The receive half is empty, which describes this transport accurately rather than leaving a gap: the work is finished by the time the dispatch returns, so there is never anything left for a worker to collect. A worker pointed here starts, finds nothing outstanding, and stops — which beats raising, because it lets one worker entrypoint serve a list of transports that happens to include sync://.

send async

send(envelope: Envelope) -> Envelope

Mark the envelope received, under the name it was sent to.

Raises:

  • UnsupportedStampError –

    If the envelope carries a :class:~xtr_messenger.stamp.DelayStamp: handling is immediate here, so a delay cannot be honoured and is refused rather than dropped.

get

get() -> AsyncIterator[Envelope]

Yield nothing — a sync transport keeps no backlog to collect.

ack async

ack(envelope: Envelope) -> None

Do nothing — nothing was ever left outstanding.

reject async

reject(envelope: Envelope) -> None

Do nothing — a failure here already reached the dispatcher.

SyncTransportFactory

Bases: TransportFactoryInterface

Builds sync:// transports, which handle in the calling process.

supports

supports(dsn: Dsn) -> bool

Recognise the sync scheme.

create

create(group: Mapping[str, TransportConfig]) -> Mapping[str, SenderInterface]

Build a sync transport per name.

Raises:

TransportConfig dataclass

TransportConfig(dsn: str, queue: str | None = None, options: Mapping[str, str] = _no_options(), failure_transport: str | None = None)

Configuration for a single named transport.

Adapter settings can be written either in the DSN's query string or in options. A DSN travels in one environment variable, which suits deployment; options survives review better once there are more than a couple, and can be built from code. Both reach the adapter through :attr:settings, so a setting can move between them without changing meaning.

Attributes:

  • dsn (str) –

    Selects the adapter and carries its connection details — sync://, in-memory:// or amqp://….

  • queue (str | None) –

    The broker queue this transport reads and writes. Transports sharing a DSN but naming different queues are what lets a worker consume one workload and ignore the rest. May also be given in the DSN as ?queue=…; this field wins when both are present.

  • options (Mapping[str, str]) –

    Adapter settings, overriding any of the same name in the DSN. Values are strings so that both sources read alike and a setting can move between them without changing meaning.

  • failure_transport (str | None) –

    The transport this one's messages are kept in once they failed for good, where the messenger:failed:* commands look for them; the configuration's own failure_transport when left out. It names the place, it does not move anything: the transport moves what failed — an orm:// transport to its failure_queue, which this then names a transport reading.

parsed property

parsed: Dsn

The DSN, read when a transport is built from it.

Not read when the config is written: a DSN usually comes from an environment variable, which a container reads only when the transport is needed.

Raises:

settings property

settings: Mapping[str, str]

Every adapter setting, from the DSN and from options, read-only.

options wins on conflict, so a DSN held in an environment variable can be overridden in code without editing it.

Raises:

queue_name property

queue_name: str | None

Return the queue this transport uses, from the field or the DSN.

TransportFactory

TransportFactory(factories: Sequence[TransportFactoryInterface] | None = None, *, serializer: SerializerInterface | None = None)

Bases: TransportFactoryInterface, PublisherClosingInterface

Builds transports by asking the factory that recognises their DSN.

A factory itself, so everything that builds a transport depends on one type whether there is a single adapter behind it or a dozen. That is what lets a bus be handed one collaborator rather than a list plus the rules for choosing from it.

Built with no list it discovers adapters by DSN scheme, loading only the one a scheme needs — an application speaking sync:// never imports a broker library. A discovered adapter that writes messages is handed serializer; one that cannot work without it is refused when its scheme is first asked for, so an application that never writes a message needs none. Given a list it uses exactly those, in order, which is how you supply an adapter that needs a collaborator discovery cannot provide::

from xtr_amqp_messenger import AmqpTransportFactory
from xtr_amqp_messenger.transport.amqp_options import AmqpOptions

TransportFactory([AmqpTransportFactory(mine, options=AmqpOptions(...))])

Delegate to factories in order, or to discovery handing over serializer.

supports

supports(dsn: Dsn) -> bool

Report whether any factory behind this one recognises dsn.

Raises:

  • MissingSerializerError –

    If the factory discovered for dsn needs the serializer this one was built without.

create

create(group: Mapping[str, TransportConfig]) -> Mapping[str, SenderInterface]

Build the senders for group with the factory that serves it.

Raises:

close_publishers async

close_publishers() -> None

Close the publish connections of every factory behind this one.

Exactly the factories this one holds, so an application closes its own connections and leaves another application's alone. A factory with no connections to release — most of them — is skipped.

serving

serving(group: Mapping[str, TransportConfig]) -> TransportFactoryInterface

Return the factory that recognises group's DSN.

Public because building a worker needs to know which adapter is in play — some bring their own, most do not.

Raises:

TransportFactoryInterface

Bases: Protocol

Builds both halves of the transports described by one connection.

One question, asked of every adapter: given these transports, build what sends to them. What consumes them is a separate concern, because most transports are consumed by the library's own loop while a few bring a worker of their own — see :class:~xtr_messenger.worker_providing_interface.WorkerProvidingInterface.

supports

supports(dsn: Dsn) -> bool

Report whether this factory recognises the scheme of dsn.

create

create(group: Mapping[str, TransportConfig]) -> Mapping[str, SenderInterface]

Build a sender for every named transport in group.

Every transport in group addresses the same server, so a factory that owns a connection can create one and share it across them.

UnsupportedDsnError

UnsupportedDsnError(transport_name: str, dsn: str)

Bases: MessageBusError

No factory recognised a transport's DSN.

Record which transport could not be built, and from what.

TransportInterface

Bases: SenderInterface, ReceiverInterface, Protocol

Both halves of a transport: what sends, and what receives.

Deliberately empty. The two halves are useful apart — a publishing process needs only :class:~xtr_messenger.transport.sender.SenderInterface, and a worker only :class:~xtr_messenger.transport.receiver.receiver_interface.ReceiverInterface — so they stay separately implementable and separately mockable. This name exists for the common case where one object is both, and for code that wants to say so in a signature.

Stating it as a base class rather than relying on structural matching means conformance is checked where the transport is defined, instead of at whatever distant call site first passes the wrong shape.

TransportLocator

TransportLocator(config: MessageBusConfig, factories: Sequence[TransportFactoryInterface] | None = None, *, receivers: Mapping[str, ReceiverInterface] | None = None)

Hands over each transport by name: the configured ones, then the registered receivers.

What the console commands reach a transport through — to set it up, count or list its messages, or read its failed ones. A configured transport is built the first time it is asked for, by the factory that serves its DSN, so building this does no I/O; a factory that keeps what it builds hands back the very transport the bus sends to. A registered receiver — one that only receives, and so has no DSN — is handed over as it was registered; a configured transport of the same name wins, as it does for a worker.

Build config's transports with factories, beside receivers.

factories means what it does for :class:~xtr_messenger.message_bus_factory.MessageBusFactory: left out, the factory serving each DSN is discovered by its scheme.

names

names() -> tuple[str, ...]

Return every name, the configured transports first, in the order they were given.

has

has(name: str) -> bool

Tell whether a transport or a receiver goes by name.

get

get(name: str) -> SenderInterface | ReceiverInterface

Return the transport name, building it the first time.

Raises:

Worker

Worker(bus: MessageBusInterface, receiver: ReceiverInterface, resetter: AsyncResetter | None = None, *, event_dispatcher: EventDispatcherInterface | None = None, receiver_name: str | None = None)

Bases: WorkerInterface

Pulls from a receiver and dispatches each message through a bus.

The loop is the whole implementation: collect an envelope, dispatch it, acknowledge it if that returned, reject it if it raised.

This makes exactly one attempt per message and never retries. That is a deliberate division of labour, not an omission. Redelivery is something only the transport can do correctly — it owns the delivery count, the backoff state, and the dead-letter destination — so a message that fails here is rejected and the transport decides what happens next. Adding a retry here would not replace that; it would run underneath it, and every failure would be attempted the product of both policies.

Dispatch messages collected from receiver through bus.

resetter, when given, has reset() awaited after each handled message — settled either way — so long-lived services (a logger's fingers-crossed buffer) are cleared between units of work. A reset that fails is logged: it changes nothing about the message, already settled, and does not stop the worker.

event_dispatcher, when given, hears about the worker and about every message — see :mod:xtr_messenger.event. receiver_name is the transport name those events report, and the one each message's :class:~xtr_messenger.stamp.ReceivedStamp carries to its handlers; left out, each envelope's own stamp names it, which is how a worker draining several transports reports each one.

run async

run() -> None

Handle each collected message, settling it either way.

Returns when the receiver stops yielding, or once :meth:stop is called — at once if the worker is waiting for a message, after settling it if one is in hand. Cancelling the task running this stops it too, and cancellation is not an Exception, so it propagates rather than being mistaken for a message that failed.

A message that raises is rejected and the loop moves on: one undeliverable message must not take the worker down with it. The failure is not lost in the process — it is attached to the rejected envelope as an :class:~xtr_messenger.stamp.ErrorDetailsStamp, so whatever the transport does with a rejection carries the reason with it.

Each message is handled — announced, dispatched, settled — in a context of its own, apart from the one this runs in. Whatever runs a worker is not its messages': a unit of work open there, a command's, would be joined by what a message does once its own unit is over — the messages it held back, a listener of its events — and shared by every message after it. Nor does a context variable one message left behind reach the next. Collecting stays where this runs: only a message is new work. It runs in one context for the whole run, copied from this one, so a receiver may set a context variable before it yields and reset it once the worker comes back for the next.

With an event dispatcher, a message a listener decides not to handle is acknowledged without being dispatched — skipping is not failing. A listener raising while a message is received or handled fails that message like a handler would; one raising while a failure is announced is a bug in the listener, so the message is rejected and the exception stops the worker. Exceptions from the started, running and stopped listeners propagate too.

stop

stop() -> None

Ask the worker to finish the message in hand and return.

Asked while not running — before :meth:run has started, say — the next run returns without collecting anything.

WorkerFactory

WorkerFactory(config: MessageBusConfig, factories: Sequence[TransportFactoryInterface] | None = None, handlers: HandlersLocatorInterface | None = None, bus: MessageBusInterface | None = None, *, logger: LoggerInterface | None = None, named: Mapping[str, MiddlewareBuilder] | None = None, resetter: AsyncResetter | None = None, event_dispatcher: EventDispatcherInterface | None = None, receivers: Mapping[str, ReceiverInterface] | None = None)

Builds what a worker process runs.

One worker serves the transports it names and nothing else, so a deployment can run a process per queue. The result is ready to run: the handlers declared with :func:~xtr_messenger.decorator.as_message_handler are already reachable from the bus it dispatches through.

What comes back is a :class:~xtr_messenger.worker_interface.WorkerInterface, never the broker underneath. That is what keeps the broker replaceable: an entrypoint says await worker.run() and never learns whether it got the library's own receive loop or one a broker library brought with it.

Build from config; bus overrides the one built for handling.

handlers replaces the process-wide registry in the bus this worker dispatches through, which is the only place a handler is called — an adapter bringing its own worker, as the AMQP one does, dispatches into that bus too.

logger and named mean what they do for :class:~xtr_messenger.message_bus_factory.MessageBusFactory: what the "logging" middleware writes through, and names of your own.

event_dispatcher is handed to every worker built, which announce themselves and each message through it — see :mod:xtr_messenger.event.

receivers are consumable by name beside the configured transports: something that only receives — messages a process generates, say — and so has no DSN to configure. A configured transport of the same name wins.

worker

worker(names: Sequence[str]) -> WorkerInterface

Build the worker for exactly the named transports.

Import the modules that declare your handlers first — a handler that has not been declared cannot be found.

A name is a configured transport or a registered receiver; a worker may consume both kinds at once, unless a configured transport brings its own worker.

Raises:

worker_for

worker_for(name: str, receiver: ReceiverInterface) -> WorkerInterface

Build the worker for receiver, consumed as the transport name.

For a receiver no configuration names — one message taken out of a transport to be retried on its own, say. It dispatches through the same bus, and resets and announces the same way, as a worker built by :meth:worker; what it receives is stamped as received from name.

WorkerInterface

Bases: Protocol

Something a worker process can run until it is stopped.

A worker is whatever consumes messages and gets them handled. That is deliberately vague about how, because the two ways differ so much: the library ships a loop that pulls from a :class:~xtr_messenger.transport.receiver.receiver_interface.ReceiverInterface, while a broker that brings its own worker — taskiq, for one — is wrapped to present this same face.

Depending on this, rather than on either implementation, is what makes a broker replaceable. An entrypoint says await worker.run() — and worker.stop() from a signal handler — and never learns which of the two it got.

run async

run() -> None

Consume and handle messages until stopped, cancelled or exhausted.

stop

stop() -> None

Ask the worker to finish the message in hand and return.

A stop asked for while the worker is not running — before :meth:run starts, say, from a task created but not yet scheduled — is not lost: the next run returns at once, without collecting anything.

WorkerProvidingInterface

Bases: Protocol

A transport factory whose broker consumes on its own terms.

Most transports are whole — they send and they receive — so a worker is simply :class:~xtr_messenger.worker.Worker driving the receive half, and the factory need not be involved. A few brokers invert that: they own the consume loop and call handlers themselves, so nothing can drive them from outside and only the adapter can build what a worker runs.

Implement this only in that second case. :class:~xtr_messenger.worker_factory.WorkerFactory prefers it when present and falls back to driving the transport itself, which is what keeps the common case free of this.

worker

worker(group: Mapping[str, TransportConfig], bus: MessageBusInterface, *, event_dispatcher: EventDispatcherInterface | None = None, resetter: AsyncResetter | None = None) -> WorkerInterface

Build what a worker process runs to consume exactly group.

event_dispatcher, when given, hears the worker events of :mod:xtr_messenger.event — for every message, and for the worker starting and stopping — the same as from the library's own worker.

resetter, when given, has reset() awaited after each message, settled either way — the contract :class:~xtr_messenger.worker.Worker honours, kept by a broker that runs its own loop too, so long-lived services are cleared between units of work whichever worker consumes.

The worker handles each message apart from the context its run() is awaited in, as the library's own do: whatever runs a worker — a console command — may have a unit of work open, and one message after another, or several at once, must not find it theirs.

declared_names

declared_names() -> tuple[str, ...]

Return the wire name of every declared message.

What a consumer that looks messages up by name — a taskiq worker registers a task per name — can expect to receive.

name_of

name_of(message_type: type) -> str

Return the wire name of message_type.

Falls back to module:QualName when no explicit name was pinned.

register_message

register_message(message_type: type, name: str | None = None, transports: tuple[str, ...] = ()) -> None

Record message_type's identity and default transport.

The storage side of :func:~xtr_messenger.decorator.as_message.as_message, kept separate so the registry can be written to without decorator syntax — for a class built dynamically, or one whose name is only known at import time.

Raises:

transports_of

transports_of(message_type: type) -> tuple[str, ...]

Return the transports message_type declares, walking its bases.

Empty when neither the class nor any of its bases declared one.

type_for_name

type_for_name(name: str) -> type

Resolve a wire name back to its declared message class.

Only declared messages resolve. The name arrives from whoever produced the message, so it is never used to import a module: a consumer decodes what it declared, and nothing else.

Raises:

declared_stamps

declared_stamps() -> tuple[type[StampInterface], ...]

Return every stamp class declared with @as_stamp, in declaration order.

register_stamp

register_stamp(stamp_type: type[StampInterface]) -> None

Record stamp_type as one serializers restore.

Raises:

  • MessageBusError –

    If another class already travels under the same class name — the header that carries a stamp names only that.

stamp_type_for

stamp_type_for(name: str) -> type[StampInterface] | None

Return the stamp class travelling as name: one the library ships, or one declared.

default_factories

default_factories(serializer: SerializerInterface | None = None) -> tuple[TransportFactoryInterface, ...]

Return every usable factory, importing all of them.

Resolution does not need this — it loads one factory per scheme on demand. Use it to compose an explicit list alongside your own::

MessageBusFactory(config, [MyFactory(), *default_factories(serializer)])

Raises: