Skip to content

xtr_messenger.bundle

The xtr-messenger bundle: wire a bus and worker factory into a kernel.

List :class:MessengerBundle in <package>/config/bundles.py. The logging and console bundles are pulled in as required bundles when installed, but the messenger keeps working without either.

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.

UnitOfWorkMiddleware

UnitOfWorkMiddleware(scopes: ScopeFactoryInterface)

Bases: MiddlewareInterface

Opens a unit of work around the rest of the chain, for one message.

The bundle puts it ahead of the configured middleware on the bus and in every worker, so the middleware after it and every handler of the message share the unit's scoped services — one database session, say — released once the message is done with. A message dispatched while another is handled joins the unit already open, and so does one a request or a command dispatches: theirs. A message a worker received is new work, a unit of its own even inside one.

The middleware holding messages back until the current one was handled comes before it, so a message held back is opened once that one's unit is over. In a worker — which handles each message apart from whatever runs it — nothing is open by then, and it is a unit of its own; where a request or a command dispatched the message that held it back, it joins theirs, as anything they dispatch does.

Open units of work through scopes — the one power, not the whole container.

handle async

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

Run the rest of the chain inside a unit of work.

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.

MessengerBundle

MessengerBundle()

Bases: Bundle[MessageBusConfig]

Turns a :class:MessageBusConfig into a bus and worker factory in the container.

Start with an empty per-kernel :class:HandlersLocator.

prepend_extension

prepend_extension(builder: ContainerBuilder) -> None

When logging is active, add the messenger channel to its config.

build

build(builder: ContainerBuilder) -> None

Autoconfigure declared handlers, named middleware and transport factories.

load_extension

load_extension(config: MessageBusConfig, services: ServiceConfigurator, builder: ContainerBuilder) -> None

Register the envelope serializer, shared TransportFactory, bus, worker factory, command.

The redispatch handler is registered here rather than declared, so the container builds it with the container's publishing bus — the factories then find a handler for :class:RedispatchMessage and add none of their own. The messages a message holds back are registered as what a new connection starts without.

process

process(builder: ContainerBuilder) -> None

Hand workers the tagged receivers; consult app-registered transport factories first.

Every service tagged :data:RECEIVER_TAG becomes consumable under its alias — aliased under :class:ReceiverInterface by that alias here, after every bundle and compiler pass before this one has registered what it will, so the worker factory's ServiceLocator[ReceiverInterface] hands each back keyed by its alias.

Autoconfiguration tags every class registered under :class:TransportFactoryInterface. When at least one exists, the shared :class:TransportFactory is rebuilt from the variant that injects them as a Sequence[TransportFactoryInterface]; with none registered the discovery-only factory loaded in :meth:load_extension stays, since the engine cannot resolve an empty collection.

boot async

boot() -> None

Bind every declared handler through the container — missing dep fails here.

shutdown async

shutdown() -> None

Close every connection a publishing transport of this kernel opened.

A producer opens its broker on first publish and nothing closes it afterwards — the consuming side's run loop does that, and a publisher has no loop. So the transport factory this kernel built is asked to release what its own senders opened.

Scoped to this kernel on purpose. Two applications can run in one process, each publishing through its own connections, and closing every connection in the process would drop one the other is still using.

An application that never resolved a transport factory built none, so there is nothing to close and no adapter is imported to be asked.