tempest_fastapi_sdk.queue¶
Fila de mensagens sobre o FastStream: publisher, consumer, topologia, retry, dedup e tracing.
queue
¶
FastStream-backed message queue primitives.
Imports the optional faststream package lazily so the rest of the
SDK remains importable when the [queue] extra is not installed.
MessageBroker is the recommended typed, transport-agnostic facade
(constructors, @on / class-based consumers, channel-first publish).
AsyncQueueManager is a minimal lifecycle wrapper around an injected
broker (renamed from AsyncBrokerManager, kept as a deprecated alias).
PublishResult
¶
Transport-specific confirmation returned by publish (or None).
Each FastStream transport returns its own confirmation type (AMQP
ConfirmationFrameType | None, Kafka RecordMetadata or future,
NATS PubAck | None, Redis int | bytes).
MessageBroker
¶
Typed, transport-agnostic publish/subscribe over FastStream.
A message broker is for event-driven fan-out between services or
workers: a producer :meth:publish-es an event to a channel and
every consumer subscribed to that channel (via :meth:on) receives
it. Delivery is at-least-once, so handlers should be idempotent.
Pick the transport with a constructor rather than importing FastStream yourself::
from pydantic import BaseModel
from tempest_fastapi_sdk.queue import MessageBroker
mq = MessageBroker.rabbitmq("amqp://guest:guest@localhost:5672/")
class OrderPaid(BaseModel):
order_id: str
@mq.on("orders.paid")
async def handle(event: OrderPaid) -> None:
await mark_paid(event.order_id)
# FastAPI lifespan
await mq.connect()
await mq.publish("orders.paid", OrderPaid(order_id="abc"))
await mq.disconnect()
The handler's type hint (event: OrderPaid) drives decoding:
FastStream validates the inbound payload into that Pydantic model
before your function runs, so a malformed message never reaches your
code. :meth:publish accepts a Pydantic model, a dict, str
or bytes — models are serialized to JSON automatically.
Attributes:
| Name | Type | Description |
|---|---|---|
broker |
BrokerUsecase[Any, Any]
|
The underlying FastStream broker — the escape hatch for transport features the facade doesn't wrap. |
Wrap an already-constructed FastStream broker.
Prefer the transport constructors (:meth:rabbitmq, :meth:redis,
:meth:kafka, :meth:nats); use this directly only to inject a
pre-configured or custom broker (e.g. a test broker).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
broker
|
BrokerUsecase[Any, Any]
|
A FastStream broker. |
required |
declare_topology
|
bool
|
Whether :meth: |
True
|
transport
property
¶
transport: TransportEnum
Return which transport this facade is wrapping.
Read from the broker class at call time, so it is correct for an injected broker as well as for one built by a constructor.
Returns:
| Name | Type | Description |
|---|---|---|
TransportEnum |
TransportEnum
|
The detected transport. |
is_connected
property
¶
Return True once :meth:connect has succeeded.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
rabbitmq
classmethod
¶
rabbitmq(
url: str,
*,
declare_topology: bool = True,
prefetch: int | None = None,
**options: Any,
) -> MessageBroker
Build a RabbitMQ-backed broker ([queue] extra).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
AMQP URL, e.g.
|
required |
declare_topology
|
bool
|
See :meth: |
True
|
prefetch
|
int | None
|
Caps how many
unacknowledged messages the broker pushes to this
connection. Without a cap the broker delivers as fast as
the consumer acks: one slow handler accumulates messages
in process memory, one replica can take the whole batch
and leave its siblings idle, and an unacked backlog is
held in RAM until the worker is OOM-killed and the whole
lot is redelivered. Per-consumer overrides go on
:meth: |
None
|
**options
|
Any
|
Extra keyword arguments forwarded to
|
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
MessageBroker |
MessageBroker
|
A facade around a |
redis
classmethod
¶
redis(url: str, *, declare_topology: bool = True, **options: Any) -> MessageBroker
Build a Redis-backed broker ([queue-redis] extra).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
Redis URL, e.g. |
required |
declare_topology
|
bool
|
See :meth: |
True
|
**options
|
Any
|
Extra keyword arguments forwarded to
|
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
MessageBroker |
MessageBroker
|
A facade around a |
kafka
classmethod
¶
kafka(
*bootstrap_servers: str, declare_topology: bool = True, **options: Any
) -> MessageBroker
Build a Kafka-backed broker ([queue-kafka] extra).
Kafka has no queues: a channel is a topic, and who gets a copy
is decided by the consumer group. Consumers sharing a
group_id (see :meth:on) split the topic's partitions between
them; each distinct group reads every record. Without a group
there is nowhere to commit an offset. A publish key (see
:meth:publish) picks the partition, so the records of one key
are read in the order they were written.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*bootstrap_servers
|
str
|
One or more |
()
|
declare_topology
|
bool
|
See :meth: |
True
|
**options
|
Any
|
Extra keyword arguments forwarded to
|
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
MessageBroker |
MessageBroker
|
A facade around a |
Raises:
| Type | Description |
|---|---|
ValueError
|
When no seed is given. FastStream accepts the empty
list and the broker fails only on |
kafka_from_settings
classmethod
¶
kafka_from_settings(
settings: KafkaSettings, *, declare_topology: bool = True, **options: Any
) -> MessageBroker
Build the Kafka broker a :class:KafkaSettings describes.
The seeds are positional on :meth:kafka and the rest comes from
:meth:~tempest_fastapi_sdk.settings.KafkaSettings.kafka_kwargs,
so a plain MessageBroker.kafka(**settings.kafka_kwargs())
would connect to FastStream's localhost default; this is the
one call that passes both halves.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
settings
|
KafkaSettings
|
The mixin, or a service |
required |
declare_topology
|
bool
|
See :meth: |
True
|
**options
|
Any
|
Extra keyword arguments forwarded to
|
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
MessageBroker |
MessageBroker
|
A facade around a |
nats
classmethod
¶
nats(
servers: str | list[str], *, declare_topology: bool = True, **options: Any
) -> MessageBroker
Build a NATS-backed broker ([queue-nats] extra).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
servers
|
str | list[str]
|
NATS server URL(s). |
required |
declare_topology
|
bool
|
See :meth: |
True
|
**options
|
Any
|
Extra keyword arguments forwarded to
|
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
MessageBroker |
MessageBroker
|
A facade around a |
on
¶
on(
channel: str | QueueSpec,
/,
*,
prefetch: int | None = None,
ack_policy: AckPolicy | None = None,
group_id: str | None = None,
auto_offset_reset: OffsetResetEnum | str | None = None,
**options: Any,
) -> Callable[[Handler], Handler]
Register the decorated async function as a consumer of channel.
The handler's parameter type hint drives decoding — annotate it with a Pydantic model and FastStream validates every inbound message into that model before the handler runs::
@mq.on("orders.paid")
async def handle(event: OrderPaid) -> None:
...
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
channel
|
str | QueueSpec
|
The logical channel to subscribe
to. Maps to a queue (RabbitMQ), topic (Kafka), subject
(NATS) or channel (Redis) under the hood. A spec with a
:class: |
required |
prefetch
|
int | None
|
Caps how many unacknowledged
messages the broker pushes to this consumer,
overriding the connection-wide cap set on
:meth: |
None
|
ack_policy
|
AckPolicy | None
|
FastStream's ack policy for this
consumer. |
None
|
group_id
|
str | None
|
Kafka consumer group. Consumers sharing it split the topic's partitions — each record goes to one of them; every distinct group gets its own copy. Kafka only. |
None
|
auto_offset_reset
|
OffsetResetEnum | str | None
|
Where the group
starts when it has no committed offset. A member or its
value ( |
None
|
**options
|
Any
|
Extra transport-specific subscriber options
forwarded to FastStream (e.g. |
{}
|
Returns:
| Type | Description |
|---|---|
Callable[[Handler], Handler]
|
Callable[[Handler], Handler]: The subscriber decorator. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When the spec has a dead-letter exchange and
|
UnsupportedTopologyError
|
When |
publish
async
¶
publish(
channel: str | QueueSpec,
message: object,
*,
exchange: ExchangeSpec | str | None = None,
key: str | bytes | None = None,
message_id: str | None = None,
**options: Any,
) -> PublishResult
Publish message to channel.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
channel
|
str | QueueSpec
|
The destination channel, or the
:class: |
required |
message
|
object
|
The payload. A Pydantic model or |
required |
exchange
|
ExchangeSpec | str | None
|
Publish to this exchange
instead of straight to the queue named |
None
|
key
|
str | bytes | None
|
Kafka record key. Records with the
same key go to the same partition, so a consumer reads
them in the order they were written; |
None
|
message_id
|
str | None
|
The id :meth: |
None
|
**options
|
Any
|
Extra transport-specific publish options
forwarded to FastStream (e.g. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
PublishResult |
PublishResult
|
Whatever the transport's publish returns (often |
PublishResult
|
|
|
PublishResult
|
are on). |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
When :meth: |
UnsupportedTopologyError
|
When |
ValueError
|
When |
declare_retry_topology
async
¶
declare_retry_topology(topology: RetryTopology) -> None
Declare and bind the three queues of a retry chain.
Declaring the queues is not enough. Each one has to be bound to its exchange, and a chain declared without the bindings routes a rejected message into an exchange with nothing behind it — where RabbitMQ drops it silently. Verified against a real broker: with the bindings the message comes back on schedule, without them it is delivered once and disappears.
Idempotent, like every AMQP declaration: re-declaring an exchange or queue with the same properties is a no-op, and re-binding an existing binding does nothing.
Call it after :meth:connect, since it needs a live channel.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
topology
|
RetryTopology
|
The
:class: |
required |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
On a transport without exchanges. The chain is AMQP-specific, and pretending otherwise would declare nothing and report success. |
dead_letter
¶
dead_letter(sink: DeadLetterSink, *, max_attempts: int = DEFAULT_MAX_ATTEMPTS) -> None
Route terminally-failed consumes to sink.
Without this, a handler that raises loses its message: the ack policy rejects it and, unless the queue declares a dead-letter exchange, the broker discards it with no error surface at all.
The sink is the same
:class:~tempest_fastapi_sdk.tasks.DeadLetterSink protocol the
task path uses, so DbDeadLetterSink and the admin panel work
unchanged and a dead task and a dead event share one screen.
Call it before :meth:connect.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sink
|
DeadLetterSink
|
Where dead events go. |
required |
max_attempts
|
int
|
Deliveries to allow before reporting.
Must match the
:class: |
DEFAULT_MAX_ATTEMPTS
|
deduplicate
¶
deduplicate(store: DedupStore, *, ttl_seconds: int = DEFAULT_DEDUP_TTL_SECONDS) -> None
Run each message id at most once, across redeliveries.
The transport is at-least-once: a restart, a requeue or a lost ack all redeliver. This claims the id before the handler runs and marks it done after, so the second delivery is skipped.
Not exactly-once. The mark and the handler's effect are not
atomic; a crash between them leaves a claim that expires and the
message runs again. When the effect is a row keyed by something
the domain owns, an INSERT ... ON CONFLICT DO NOTHING is
idempotent with no extra moving part and is the better answer.
Call it before :meth:connect.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
store
|
DedupStore
|
A
:class: |
required |
ttl_seconds
|
int
|
How long an id is remembered. Must outlive the retry topology's total delay, or the last retry runs as if the message were new. |
DEFAULT_DEDUP_TTL_SECONDS
|
enable_tracing
¶
Open a span per consumed message, linked to the publish.
:meth:publish already injects the trace context and the current
request id into the message headers; this is the other half —
each consume runs inside a span carrying the messaging semantic
conventions, linked to the publishing trace rather than
parented by it, and with the publisher's request id restored so
the worker's log lines carry it.
A no-op without the [otel] extra, and non-recording when the
extra is present but no provider was configured. Request-id
propagation works either way.
Call it before :meth:connect.
enable_metrics
¶
enable_metrics(metrics: QueueMetrics) -> None
Publish consume counts and durations for every channel.
Call it before :meth:connect.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metrics
|
QueueMetrics
|
A
:class: |
required |
register
¶
register(consumer: Consumer) -> None
Wire a class-based :class:Consumer onto this broker.
Reads every binding the consumer declares (constructor form or
grouped @subscribe methods — see
:class:~tempest_fastapi_sdk.queue.Consumer) and subscribes each
handler to its channel. When a binding carries an explicit
schema (the constructor form), that model drives decoding;
otherwise the handler's own type hint does.
A binding's prefetch goes through the same translation
:meth:on applies — FastStream carries the cap on a Channel
object and has no prefetch keyword, so forwarding it verbatim
raises TypeError instead of capping anything.
A binding's ack_policy, group_id and auto_offset_reset
are resolved — and refused — exactly as :meth:on does it.
Call it at import/startup time, before :meth:connect.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
consumer
|
Consumer
|
The consumer instance to register. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
When a spec with a dead-letter exchange is bound
under an ack policy that never dead-letters, or a Kafka
binding commits without a |
UnsupportedTopologyError
|
When a binding sets a knob its transport cannot express. |
publisher
¶
publisher(channel: str | QueueSpec, /, **options: Any) -> QueuePublisher
Return a reusable publisher bound to channel.
Useful to declare a typed outbound endpoint once and call it
many times, and so the channel shows up in FastStream's AsyncAPI
docs. The returned object is called as await pub.publish(msg).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
channel
|
str | QueueSpec
|
The destination channel. |
required |
**options
|
Any
|
Extra transport-specific publisher options. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
QueuePublisher |
QueuePublisher
|
A FastStream publisher object bound to |
QueuePublisher
|
|
publisher_for
¶
publisher_for(
publisher: type[PublisherT],
*,
channel: str | QueueSpec | None = None,
schema: type | None = None,
**options: Any,
) -> PublisherT
Bind a class-based :class:Publisher to this broker.
The publish-side counterpart of :meth:register, and the reason
it takes a class rather than an instance: a
:class:~tempest_fastapi_sdk.queue.Publisher is useless until it
has a broker, so constructing it separately would only create a
window in which it exists and cannot publish.
The declared channel goes through the same binding
:meth:on uses, so a
:class:~tempest_fastapi_sdk.queue.QueueSpec is validated against
the transport here, at startup, and registered for
:meth:declare_topology. Without that, a service that only
publishes would name a dead-letter exchange nobody declares — and
every rejected message on the consuming side would be dropped at
routing time, silently.
channel and schema are named rather than left to
**options so the type checker sees them and a publish option
that happens to share one of those names is not swallowed. They
override whatever the class declares, which is what lets one
Publisher subclass serve a channel only known at runtime —
per tenant, per environment — without a subclass per value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
publisher
|
type[PublisherT]
|
The |
required |
channel
|
str | QueueSpec | None
|
Overrides the class attribute. Required when the class declares none. |
None
|
schema
|
type | None
|
Overrides the class attribute. |
None
|
**options
|
Any
|
Default publish options for every message it sends. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
PublisherT |
PublisherT
|
The bound instance. |
Raises:
| Type | Description |
|---|---|
UnsupportedTopologyError
|
When the declared spec sets a field the transport cannot honor. |
connect
async
¶
Start the broker so consumers and publishers go live.
Idempotent — safe to call from the FastAPI lifespan and again elsewhere; extra calls are no-ops while the broker is alive.
On RabbitMQ the connection is opened and :meth:declare_topology
runs before the subscribers start. The other order left a
window in which a consumer was already receiving and its
dead-letter exchange did not exist yet: a message rejected in it
was routed nowhere and dropped. A declaration the broker refuses
(PRECONDITION_FAILED on a queue that exists with other
arguments) therefore surfaces before any consumer runs, and the
connection opened for it is closed before the error propagates.
declare_topology
async
¶
Declare the dead-letter exchanges and queues the specs name.
A queue carrying x-dead-letter-exchange is declared happily
by RabbitMQ even when that exchange does not exist — and then
every rejected message is dropped at routing time, silently. The
same happens when the exchange exists and no queue is bound
to it: routing finds no destination and the message is gone. So
the exchange is declared, and a spec whose
:class:~tempest_fastapi_sdk.queue.DeadLetterSpec names a
queue gets that queue declared and bound under its routing
key. :meth:connect calls this before the subscribers start,
unless the broker was built with declare_topology=False.
Idempotent: declaring an exchange that already exists with the same properties is a no-op in AMQP. Only durable topic exchanges are declared, which is what a dead-letter exchange should be — a non-durable one would vanish on restart and take the routing with it.
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: The exchange names declared, in sorted order. |
list[str]
|
Empty on a transport with no such concept, or when no spec |
list[str]
|
asked for dead-lettering. |
replay_dead_letters
async
¶
replay_dead_letters(
source: QueueSpec | RetryTopology | str,
*,
into: str | None = None,
limit: int = DEFAULT_REPLAY_LIMIT,
) -> int
Move dead-lettered messages back to the queue they failed on.
For after the fix: each message is read from the dead-letter queue, republished straight to the origin queue through the default exchange — never to the shared exchange, which would hand a second copy to every other consumer of the event — and only then acknowledged. A publish that fails puts the message back on the dead-letter queue and stops the run, so a message is never acknowledged without having been delivered somewhere. The origin queue is checked first: through the default exchange, a publish to a queue that does not exist raises nothing — the broker hands the message back as unroutable — and acking after it would lose it.
What travels: the body as bytes, message_id (the
deduplication key, so a consumer with
:meth:deduplicate still recognises it), content_type,
content_encoding, correlation_id, priority,
timestamp, type, reply_to and the headers, persisted.
expiration, app_id and user_id do not: a replay is a
new delivery, not a resurrection of the old one's lifetime;
FastStream's publish takes no app_id; and the broker checks
user_id against the replaying connection's login, so the
original's would be refused. The broker's x-death
bookkeeping is dropped: the retry middleware counts attempts from
it, and a replayed message that kept it would be given up on at
its first failure instead of getting a fresh budget.
At least once, not exactly once: when the publish succeeds and the
ack that follows fails (the connection drops between them),
the message is both back on the origin queue and still on the
dead-letter queue, and the next replay delivers it again. A
consumer with :meth:deduplicate skips the second copy by its
message_id.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
QueueSpec | RetryTopology | str
|
Where the dead
messages are. A spec built with a dead-letter |
required |
into
|
str | None
|
The queue to return messages to. Only for a bare name; the other forms already say. |
None
|
limit
|
int
|
Most messages to move in this call. A message that fails again lands back on the dead-letter queue behind the others, so without a cap a still-broken consumer turns the replay into a loop. |
DEFAULT_REPLAY_LIMIT
|
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
How many messages went back. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
NotImplementedError
|
On a transport without queues to read from. |
RuntimeError
|
When :meth: |
ChannelNotFoundEntity
|
When the dead-letter queue or the origin queue does not exist. Nothing is read. |
disconnect
async
¶
Stop the broker and release its connections.
Forgets which exchanges :meth:publish declared, so the next
:meth:connect declares them again rather than trusting a
connection that is gone.
lifespan
async
¶
lifespan() -> AsyncGenerator[MessageBroker, None]
Connect on entry, disconnect on exit — for scripts and tests.
Long-lived apps should call :meth:connect / :meth:disconnect
from their own FastAPI lifespan instead.
Yields:
| Name | Type | Description |
|---|---|---|
MessageBroker |
AsyncGenerator[MessageBroker, None]
|
This connected facade. |
broker_dependency
async
¶
broker_dependency() -> AsyncIterator[MessageBroker]
FastAPI Depends provider yielding this connected facade.
Yields:
| Name | Type | Description |
|---|---|---|
MessageBroker |
AsyncIterator[MessageBroker]
|
This facade. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
When :meth: |
health_check
async
¶
Report whether the broker connection is alive right now.
Delegates to the FastStream broker's own ping(timeout), which
every transport implements: RabbitMQ and NATS read the live
connection state, Redis sends a PING and Kafka asks the
cluster for its metadata. A connection that dropped after
:meth:connect therefore reports False. Before
:meth:connect (or after :meth:disconnect) it returns
False without touching the network. Wire it into a readiness
probe with make_health_router(checks={"queue": mq.health_check});
the default timeout stays below the router's per-check bound.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timeout
|
float
|
Seconds the ping may take before it gives up
and reports |
2.0
|
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
bool
|
answered within |
QueuePublisher
¶
Bases: Protocol
Minimal surface of a publisher from :meth:MessageBroker.publisher.
publish
¶
publish(message: object, /, **kwargs: Any) -> Awaitable[PublishResult]
Publish message through the bound channel.
Consumer
¶
Consumer(
*,
channel: str | QueueSpec | None = None,
schema: type | None = None,
prefetch: int | None = None,
ack_policy: AckPolicy | None = None,
group_id: str | None = None,
auto_offset_reset: OffsetResetEnum | str | None = None,
**options: Any,
)
Bases: Generic[MessageT]
Base class for class-based message consumers.
Subclass it in one of the two styles shown in the module docstring.
Both are explicit — nothing is inferred from the class name. Register
an instance with
:meth:~tempest_fastapi_sdk.queue.MessageBroker.register.
Attributes:
| Name | Type | Description |
|---|---|---|
channel |
str | QueueSpec | None
|
The channel for the constructor
form, or the |
schema |
type | None
|
The payload model for the constructor form. |
prefetch |
int | None
|
Unacknowledged-message cap for every
binding this consumer declares. A :func: |
ack_policy |
AckPolicy | None
|
Ack policy for every binding, with
the same override rule as :attr: |
group_id |
str | None
|
Kafka consumer group for every binding,
with the same override rule as :attr: |
auto_offset_reset |
OffsetResetEnum | str | None
|
Where that group starts without a committed offset, same override rule. Kafka only. |
options |
dict[str, Any]
|
Subscriber options for the constructor form. Never mutated, so the empty class-level default is safe to share. |
Configure the constructor form.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
channel
|
str | QueueSpec | None
|
The channel to consume, or
the |
None
|
schema
|
type | None
|
The Pydantic model the payload is validated into. Passing it here is the explicit, no-magic path — it drives decoding instead of relying on an annotation. |
None
|
prefetch
|
int | None
|
Caps how many unacknowledged messages
the broker pushes to this consumer, the same knob
:meth: |
None
|
ack_policy
|
AckPolicy | None
|
Ack policy for every binding,
unless a :func: |
None
|
group_id
|
str | None
|
Kafka consumer group for every binding,
unless a :func: |
None
|
auto_offset_reset
|
OffsetResetEnum | str | None
|
Where that group
starts without a committed offset, unless a
:func: |
None
|
**options
|
Any
|
Extra transport-specific subscriber options
forwarded to FastStream (e.g. |
{}
|
handle
async
¶
Handle one message — override in the constructor form.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
MessageT
|
The decoded payload (an instance of
:attr: |
required |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
When neither |
subscriptions
¶
subscriptions() -> list[Subscription]
Return every channel → handler binding this consumer declares.
Grouped @subscribe methods take precedence; if none are
present, the constructor form (channel + handle) is used.
A binding with no prefetch of its own inherits
:attr:prefetch; the same goes for ack_policy, group_id
and auto_offset_reset.
Returns:
| Type | Description |
|---|---|
list[Subscription]
|
list[Subscription]: One entry per subscription. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When the consumer declares neither a |
Subscription
dataclass
¶
Subscription(
channel: str | QueueSpec,
handler: Callable[..., Awaitable[Any]],
schema: type | None,
options: dict[str, Any],
prefetch: int | None = None,
ack_policy: AckPolicy | None = None,
group_id: str | None = None,
auto_offset_reset: OffsetResetEnum | str | None = None,
)
One channel → handler binding produced by a :class:Consumer.
Attributes:
| Name | Type | Description |
|---|---|---|
channel |
str | QueueSpec
|
The channel to subscribe on, or the spec declaring it. |
handler |
Callable[..., Awaitable[Any]]
|
The async callable that receives each decoded message. |
schema |
type | None
|
Explicit payload model. When set, it drives
decoding regardless of the handler's annotation; when |
options |
dict[str, Any]
|
Extra transport-specific subscriber options. |
prefetch |
int | None
|
Per-consumer unacknowledged-message cap,
kept apart from :attr: |
ack_policy |
AckPolicy | None
|
The ack policy asked for, resolved
by :meth: |
group_id |
str | None
|
The Kafka consumer group asked for. |
auto_offset_reset |
OffsetResetEnum | str | None
|
Where that group starts without a committed offset. |
ConcurrentDeliveryError
¶
Bases: RuntimeError
The same message id is already being processed elsewhere.
Raised so the broker rejects the duplicate rather than acknowledging it. Acknowledging would be the dangerous choice: the in-flight worker may still fail, and the copy that could have retried would be gone.
DedupStateEnum
¶
Bases: BaseStrEnum
What the store knew about a message id when it was claimed.
Attributes:
| Name | Type | Description |
|---|---|---|
NEW |
Never seen. The handler runs. |
|
IN_FLIGHT |
Another delivery of the same id is being processed. The
handler does not run and the message is rejected, so the
retry topology offers it again later — by which time the
other worker has either finished ( |
|
DONE |
Already processed successfully. The handler does not run and the message is acknowledged. |
DedupStore
¶
Bases: Protocol
Where processed message ids are remembered.
Three operations, because two-phase marking needs them. :meth:claim
must be atomic — two workers claiming the same id concurrently
must not both receive :attr:DedupStateEnum.NEW, which is why it is one
call rather than a get followed by a set.
claim
async
¶
claim(key: str, *, ttl_seconds: int) -> DedupStateEnum
Mark key in-flight if it is unseen, and report what it was.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The message id. |
required |
ttl_seconds
|
int
|
How long the mark lives. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
DedupStateEnum |
DedupStateEnum
|
What the store held before this call. |
complete
async
¶
Mark key as successfully processed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The message id. |
required |
ttl_seconds
|
int
|
How long to remember it. |
required |
release
async
¶
Forget key so a later delivery processes it again.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The message id. |
required |
MemoryDedupStore
dataclass
¶
In-process :class:DedupStore, for one replica and for tests.
Correct only while a single process consumes the channel — two
replicas each keep their own table and neither sees the other's
claims, so a redelivery routed to the sibling runs the handler again.
Use :class:RedisDedupStore for anything with more than one worker.
Attributes:
| Name | Type | Description |
|---|---|---|
entries |
MutableMapping[str, tuple[str, float]]
|
Key to
|
claim
async
¶
claim(key: str, *, ttl_seconds: int) -> DedupStateEnum
Claim key, reporting what the store already held.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The message id. |
required |
ttl_seconds
|
int
|
How long the mark lives. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
DedupStateEnum |
DedupStateEnum
|
The prior state. |
complete
async
¶
Mark key done.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The message id. |
required |
ttl_seconds
|
int
|
How long to remember it. |
required |
release
async
¶
Drop key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The message id. |
required |
RedisDedupStore
¶
:class:DedupStore backed by an async redis client.
:meth:claim is a single SET key in_flight NX EX ttl, so the
atomicity two-phase marking depends on comes from Redis rather than
from a lock of our own — two workers racing on the same id cannot
both be told NEW.
Wrap a Redis client.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
Any
|
An async |
required |
prefix
|
str
|
Key namespace, so dedup keys never collide with the application's own. |
'tempest:dedup:'
|
claim
async
¶
claim(key: str, *, ttl_seconds: int) -> DedupStateEnum
Claim key atomically via SET NX.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The message id. |
required |
ttl_seconds
|
int
|
How long the mark lives. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
DedupStateEnum |
DedupStateEnum
|
The prior state. A lost race reads the current |
DedupStateEnum
|
value to tell |
|
DedupStateEnum
|
between the two calls reads as |
|
DedupStateEnum
|
message rather than running it twice — the safer way to be |
|
DedupStateEnum
|
wrong for a handler that is not free to repeat. |
complete
async
¶
Mark key done.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The message id. |
required |
ttl_seconds
|
int
|
How long to remember it. |
required |
release
async
¶
Drop key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The message id. |
required |
AsyncQueueManager
¶
Manage the lifecycle of an injected FastStream broker.
A minimal wrapper: it wraps any FastStream broker (RabbitBroker,
KafkaBroker, NatsBroker, RedisBroker, etc.) with a uniform connect /
disconnect / health-check surface matching the SDK's other backends,
and forwards publish. Reach for it when you already build your own
broker and only want lifecycle management.
For the batteries-included experience — transport constructors, a
typed @on(channel) consumer decorator, class-based consumers and
channel-first publish — use
:class:~tempest_fastapi_sdk.queue.MessageBroker instead.
The broker is injected so consumers stay free to choose the transport without forcing FastStream to import every backend.
Typical usage::
from faststream.rabbit import RabbitBroker
from tempest_fastapi_sdk import AsyncQueueManager
broker = RabbitBroker("amqp://guest:guest@localhost:5672/")
queue = AsyncQueueManager(broker)
@queue.broker.subscriber("orders")
async def handle(msg: OrderMessage) -> None:
...
# FastAPI lifespan
await queue.connect()
...
await queue.disconnect()
Attributes:
| Name | Type | Description |
|---|---|---|
broker |
BrokerUsecase[Any, Any]
|
The wrapped broker instance. |
Initialize the manager.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
broker
|
BrokerUsecase[Any, Any]
|
A FastStream broker instance. Construct it with whatever transport-specific configuration the application needs. |
required |
is_connected
property
¶
Return True once :meth:connect succeeded.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
connect
async
¶
Start the broker so subscribers and publishers are live.
Safe to call multiple times — subsequent calls are no-ops while the same broker is alive.
publish
async
¶
publish(message: object, *args: Any, **kwargs: Any) -> PublishResult
Publish message through the underlying broker.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
object
|
The payload to publish. Forwarded as-is. |
required |
*args
|
Any
|
Positional broker-specific arguments (queue, exchange, topic, etc.). |
()
|
**kwargs
|
Any
|
Keyword broker-specific arguments. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
PublishResult |
PublishResult
|
Whatever the broker's |
PublishResult
|
(often |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
When :meth: |
lifespan
async
¶
Yield the broker inside an async with block.
Connects on entry, disconnects on exit. Convenient for short
scripts and tests; long-lived applications should call
:meth:connect / :meth:disconnect from their own lifespan.
Yields:
| Type | Description |
|---|---|
AsyncGenerator[BrokerUsecase[Any, Any], None]
|
BrokerUsecase[Any, Any]: The connected broker. |
broker_dependency
async
¶
Async generator dependency suitable for FastAPI Depends.
Yields:
| Type | Description |
|---|---|
AsyncIterator[BrokerUsecase[Any, Any]]
|
BrokerUsecase[Any, Any]: The connected broker. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
When :meth: |
health_check
async
¶
Report whether the broker connection is alive right now.
Delegates to the FastStream broker's own ping(timeout), so a
connection that dropped after :meth:connect reports False.
Before :meth:connect (or after :meth:disconnect) it returns
False without touching the network.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timeout
|
float
|
Seconds the ping may take before it gives up
and reports |
2.0
|
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
bool
|
answered within |
Publisher
¶
Publisher(
broker: MessageBroker,
*,
channel: str | QueueSpec | None = None,
schema: type | None = None,
**options: Any,
)
Bases: Generic[MessageT]
Base class for class-based publishers, bound to one channel.
Subclass it with the channel and the payload model, then obtain an
instance from
:meth:~tempest_fastapi_sdk.queue.MessageBroker.publisher_for. The
constructor form works too, for a channel only known at runtime::
orders = Publisher[OrderPaid](
mq, channel="orders.paid", schema=OrderPaid,
)
Nothing is inferred from the class name — same rule as
:class:~tempest_fastapi_sdk.queue.Consumer.
Attributes:
| Name | Type | Description |
|---|---|---|
channel |
str | QueueSpec | None
|
The destination. A
:class: |
schema |
type | None
|
The payload model. When set, :meth: |
Bind this publisher to a broker.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
broker
|
MessageBroker
|
The facade to publish through. |
required |
channel
|
str | QueueSpec | None
|
Overrides the class attribute. Required when the class does not declare one. |
None
|
schema
|
type | None
|
Overrides the class attribute. |
None
|
**options
|
Any
|
Default publish options merged into every
:meth: |
{}
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When neither the class nor the constructor names a channel, since there would be nowhere to publish to. |
publish
async
¶
publish(
message: MessageT, *, key: str | bytes | None = None, **options: Any
) -> PublishResult
Publish message to this publisher's channel.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
MessageT
|
The payload. Validated against
:attr: |
required |
key
|
str | bytes | None
|
Kafka record key, exactly as
:meth: |
None
|
**options
|
Any
|
Extra publish options for this message, overriding the defaults given to the constructor. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
PublishResult |
PublishResult
|
Whatever the transport's publish returns. |
Raises:
| Type | Description |
|---|---|
TypeError
|
When :attr: |
RuntimeError
|
When the broker is not connected. |
UnsupportedTopologyError
|
When |
ConsumerRetryPolicy
dataclass
¶
ConsumerRetryPolicy(
max_attempts: int = DEFAULT_MAX_ATTEMPTS, delay_ms: int = DEFAULT_RETRY_DELAY_MS
)
How many times to retry a failing consumer, and how long to wait.
Attributes:
| Name | Type | Description |
|---|---|---|
max_attempts |
int
|
Total deliveries, including the first. |
delay_ms |
int
|
Milliseconds a message waits before being offered again. |
QueueMetrics
¶
Prometheus counters and durations for consumed messages.
Mirrors :class:~tempest_fastapi_sdk.tasks.TaskMetrics so the event
path and the task path graph the same way, on the same registry and
the same /metrics endpoint:
queue_messages_total{channel,status}—statusisok,error, orduplicatefor a delivery :meth:~tempest_fastapi_sdk.queue.MessageBroker.deduplicaterejected because a sibling worker held the claim. Its own label keeps a normal dedup outcome out of the error rate an alert reads.queue_message_duration_seconds{channel}— handler wall time.
Without this, the consumer failure rate is invisible: the message is rejected, the broker discards or dead-letters it, and nothing counts.
Register the two collectors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
registry
|
CollectorRegistry | None
|
Registry to register on.
|
None
|
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
middleware
¶
Build the FastStream middleware that feeds these collectors.
Returns:
| Type | Description |
|---|---|
type[BaseMiddleware]
|
type[BaseMiddleware]: A |
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
RetryTopology
dataclass
¶
RetryTopology(
main: QueueSpec,
retry: QueueSpec,
dead: QueueSpec,
channel: str,
main_exchange: str,
retry_exchange: str,
dead_exchange: str,
)
The three queues a retried channel needs.
Carries the exchange names as well as the queues, because the queues
alone are not a working topology: each has to be bound to its
exchange, and a chain declared without the bindings routes a rejected
message into an exchange with nothing behind it — where RabbitMQ
silently drops it. See
:meth:~tempest_fastapi_sdk.queue.MessageBroker.declare_retry_topology.
Attributes:
| Name | Type | Description |
|---|---|---|
main |
QueueSpec
|
What the consumer subscribes to. Dead-letters to the retry exchange when the handler rejects. |
retry |
QueueSpec
|
The waiting room. Holds nothing but a TTL; when a message expires it is dead-lettered back to the main exchange, which is what makes the delay work without a plugin. |
dead |
QueueSpec
|
Terminal. Nothing routes out of it — it is read by a human, or by the admin panel. |
channel |
str
|
The routing key every binding uses. |
main_exchange |
str
|
Exchange the main queue is bound to. |
retry_exchange |
str
|
Exchange the retry queue is bound to. |
dead_exchange |
str
|
Exchange the dead queue is bound to. |
DeadLetterSpec
dataclass
¶
Where a rejected message goes.
On RabbitMQ, dead-lettering is a property of the queue, not of
the consumer: the broker routes a message to exchange when it is
rejected without requeue, expires, or overflows the queue length.
Without it, a rejected message is discarded — which is the default
and is silent.
Naming a :attr:queue makes the topology complete: the exchange
and that queue are declared and bound before any subscriber
starts, so a message rejected on the first delivery already has
somewhere to go. Leave it None when something else consumes the
exchange — the delayed-retry chain of
:func:~tempest_fastapi_sdk.queue.retry_queues is the case: its
retry queue is bound there, and a second queue under the same key
would receive a duplicate of every failure.
Attributes:
| Name | Type | Description |
|---|---|---|
exchange |
str
|
The exchange rejected messages are published to.
Declared by
:meth: |
routing_key |
str | None
|
Routing key to use when dead-lettering.
|
queue |
str | None
|
The dead-letter queue to declare and bind to
:attr: |
ExchangeBinding
dataclass
¶
ExchangeBinding(exchange: ExchangeSpec, routing_key: str)
Bind a queue to an exchange under a routing key.
This is what turns one published event into one copy per consumer: each consumer's queue is bound to the same exchange with the same key, and the broker delivers to every bound queue. Without a binding, two consumers subscribing to the same queue name share one queue and split the messages between them instead.
Attributes:
| Name | Type | Description |
|---|---|---|
exchange |
ExchangeSpec
|
The exchange to bind to. Declared when the subscriber starts. |
routing_key |
str
|
The key (a pattern, on a topic exchange) the queue receives. |
ExchangeKindEnum
¶
Bases: BaseStrEnum
AMQP exchange type.
Mirrors faststream.rabbit.ExchangeType value for value, so the
topology module imports nothing from FastStream and stays importable
without the [queue] extra.
Attributes:
| Name | Type | Description |
|---|---|---|
TOPIC |
Routes by pattern ( |
|
DIRECT |
Routes by exact key. |
|
FANOUT |
Ignores the key; every bound queue gets a copy. |
|
HEADERS |
Routes by message headers. |
ExchangeSpec
dataclass
¶
ExchangeSpec(name: str, kind: ExchangeKindEnum = TOPIC, durable: bool = True)
An exchange to publish to or bind a queue to.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
The exchange name. |
kind |
ExchangeKindEnum
|
The exchange type. |
durable |
bool
|
Whether it survives a broker restart. |
OffsetResetEnum
¶
Bases: BaseStrEnum
Where a Kafka consumer group starts when it has no committed offset.
Only read when the group has never committed on a partition (a new group, or offsets expired by the broker's retention). A group that committed resumes from its commit whatever this says.
Attributes:
| Name | Type | Description |
|---|---|---|
LATEST |
Start at the end — only records written after the consumer joined are read. Kafka's and FastStream's default, and the reason a brand-new consumer misses everything that was published before its first deploy. |
|
EARLIEST |
Start at the oldest record the topic still retains. |
|
NONE |
Refuse to start without a committed offset. |
QueueSpec
dataclass
¶
QueueSpec(
name: str,
durable: bool = True,
dead_letter: DeadLetterSpec | None = None,
message_ttl_ms: int | None = None,
max_priority: int | None = None,
max_length: int | None = None,
queue_type: QueueTypeEnum = CLASSIC,
binding: ExchangeBinding | None = None,
)
A channel plus the topology it needs.
Accepted anywhere a channel string is, so adopting it is per-channel rather than all-or-nothing.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
The channel name. The only required field, and the only one every transport understands. |
durable |
bool
|
Whether the queue survives a broker restart.
|
dead_letter |
DeadLetterSpec | None
|
Where rejected messages go. |
message_ttl_ms |
int | None
|
Discard (or dead-letter) a message after this many milliseconds. |
max_priority |
int | None
|
Enable a priority queue with this many
levels. Incompatible with :attr: |
max_length |
int | None
|
Cap the queue at this many messages;
overflow is dead-lettered when :attr: |
queue_type |
QueueTypeEnum
|
Classic or quorum. |
binding |
ExchangeBinding | None
|
Bind the queue to an exchange
under a routing key, so it receives its own copy of what is
published there. |
consumer
classmethod
¶
consumer(
consumer: str,
channel: str,
*,
exchange: ExchangeSpec | str,
dead_letter_exchange: str | None = None,
queue_type: QueueTypeEnum = CLASSIC,
) -> QueueSpec
Build one consumer's queue for an event published to exchange.
The fan-out shape: every module that reacts to channel gets
its own durable queue, <consumer>.<channel>, bound to the
shared exchange under channel — so each receives a copy
instead of competing for one.
With dead_letter_exchange, a rejected message is routed there
under the queue name (not the event key, which every consumer
shares) into <consumer>.<channel>.dlq, and both are declared
before the subscribers start. Replay it with
:meth:~tempest_fastapi_sdk.queue.MessageBroker.replay_dead_letters,
which returns it to this queue only.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
consumer
|
str
|
The consuming module, e.g. |
required |
channel
|
str
|
The event's routing key, e.g.
|
required |
exchange
|
ExchangeSpec | str
|
The exchange the event is published to. A bare name is a durable topic exchange. |
required |
dead_letter_exchange
|
str | None
|
Exchange rejected messages
go to, or |
None
|
queue_type
|
QueueTypeEnum
|
Classic or quorum. |
CLASSIC
|
Returns:
| Name | Type | Description |
|---|---|---|
QueueSpec |
QueueSpec
|
The spec to pass to |
QueueSpec
|
meth: |
QueueTypeEnum
¶
Bases: BaseStrEnum
RabbitMQ queue implementation.
Attributes:
| Name | Type | Description |
|---|---|---|
CLASSIC |
The default. One queue master, mirrored only if a policy says so. |
|
QUORUM |
Raft-replicated across nodes. Survives the loss of a node
without the message loss classic mirroring can suffer, at the
cost of memory and of not supporting |
TransportEnum
¶
Bases: BaseStrEnum
Which broker a :class:QueueSpec is being translated for.
Detected from the FastStream broker class rather than recorded at
construction, so a :class:~tempest_fastapi_sdk.queue.MessageBroker
built by injecting a broker directly is classified the same way as
one built through a transport constructor.
UnsupportedTopologyError
¶
Bases: RuntimeError
A :class:QueueSpec asks for something the transport cannot do.
Raised where the queue is bound — :meth:~MessageBroker.on,
:meth:~MessageBroker.publisher, :meth:~MessageBroker.register —
which is startup, not per message, so the mismatch surfaces on the
first run rather than as a queue that quietly lacks the property you
declared. :meth:~MessageBroker.publish only reads the name, since
the topology belongs to the declaration and not to the message.
consume_span
¶
Span around one consumed message, linked to the publishing trace.
Follows the OpenTelemetry messaging semantic conventions:
messaging.system, messaging.destination.name and
messaging.operation, with the span named "<channel> process".
The publishing trace is attached as a link, not as a parent. The convention recommends it for asynchronous consumption, and the reason is practical: a consumer can run minutes after the publish, and a child span of that duration would stretch the request's trace and make its latency unreadable. A link keeps both traces truthful and still lets you jump between them.
Restores the publisher's request id for the duration of the block, so
the worker's log lines carry the id of the request that caused them —
which is worth more than the span to anyone debugging with grep.
Prepare a span for a message on channel.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
channel
|
str
|
The queue/topic the message arrived on. |
required |
headers
|
dict[str, Any] | None
|
The message headers, read for the trace context and the request id. |
None
|
subscribe
¶
subscribe(
channel: str | QueueSpec,
*,
prefetch: int | None = None,
ack_policy: AckPolicy | None = None,
group_id: str | None = None,
auto_offset_reset: OffsetResetEnum | str | None = None,
**options: Any,
) -> Callable[[Callable[..., Awaitable[Any]]], Callable[..., Awaitable[Any]]]
Mark a :class:Consumer method as the handler for channel.
The decorated method keeps its normal signature — its message
parameter's type hint is what validates the payload. Only used in the
grouped form; the constructor form overrides :meth:Consumer.handle
instead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
channel
|
str | QueueSpec
|
The channel this method consumes, or
the |
required |
prefetch
|
int | None
|
Caps how many unacknowledged messages the
broker pushes to this handler, exactly as
:meth: |
None
|
ack_policy
|
AckPolicy | None
|
FastStream's ack policy for this
handler, resolved as
:meth: |
None
|
group_id
|
str | None
|
Kafka consumer group for this handler, as
:meth: |
None
|
auto_offset_reset
|
OffsetResetEnum | str | None
|
Where the group starts
without a committed offset. Overrides
:attr: |
None
|
**options
|
Any
|
Extra transport-specific subscriber options
forwarded to FastStream (e.g. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
Callable |
Callable[[Callable[..., Awaitable[Any]]], Callable[..., Awaitable[Any]]]
|
The same method, tagged so |
delivery_attempt
¶
Return which delivery this is, counting from 1.
RabbitMQ records every dead-lettering in the message's x-death
header, so the number of times a message has already been rejected is
readable without any state of our own — which matters, because a
consumer restart must not reset the budget.
Entries whose reason is "expired" are skipped, and that is
load-bearing rather than a detail. RabbitMQ keeps one entry per
(queue, reason) pair, and the delayed-retry chain dead-letters a
message twice per round: once out of the main queue (rejected)
and once out of the retry queue when its TTL fires (expired).
Summing every entry therefore advanced the counter by two per retry,
so a max_attempts=3 policy gave up after two deliveries. An
expiry is the waiting room emptying itself, not a delivery that
failed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
object
|
The FastStream message being consumed. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
|
int
|
on. Falls back to |
|
int
|
so an unreadable header costs an extra attempt rather than |
|
int
|
dropping the message early. |
retry_queues
¶
retry_queues(
channel: str,
policy: ConsumerRetryPolicy | None = None,
*,
retry_exchange: str,
main_exchange: str,
dead_exchange: str,
queue_type: QueueTypeEnum = CLASSIC,
) -> RetryTopology
Build the delayed-retry topology for channel.
RabbitMQ has no per-message delay of its own. The portable way to get
one is a pair of queues: the main queue dead-letters a rejected
message into a retry queue whose only job is to hold it, and that
queue's TTL dead-letters it back to the main exchange when it
expires. The message therefore reappears at the consumer delay_ms
later, with the broker doing the waiting — so a worker restart in the
meantime changes nothing.
The alternative is the rabbitmq_delayed_message_exchange plugin,
which is simpler to declare and requires the plugin installed —
not available on several managed offerings, including the free
CloudAMQP tier. This builds on stock AMQP instead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
channel
|
str
|
The channel the consumer subscribes to. |
required |
policy
|
ConsumerRetryPolicy | None
|
Attempts and delay. Defaults
to :class: |
None
|
retry_exchange
|
str
|
Exchange the main queue dead-letters to. |
required |
main_exchange
|
str
|
Exchange the retry queue returns messages
to. Must route back to |
required |
dead_exchange
|
str
|
Exchange the terminal queue is fed from. |
required |
queue_type
|
QueueTypeEnum
|
Queue implementation for all three. |
CLASSIC
|
Returns:
| Name | Type | Description |
|---|---|---|
RetryTopology |
RetryTopology
|
The three specs, ready to declare and subscribe. |
Notes
max_attempts is not enforced by this topology — AMQP
counts redeliveries in the x-death header but will not stop
on its own. The count is enforced by the consumer middleware
(:func:make_dead_letter_middleware), which reads that header
and routes to the dead queue once the budget is spent. Declaring
the topology without installing the middleware yields infinite
retries, which is why they are documented together.
extract_context
¶
Recover the publishing trace context from headers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
headers
|
dict[str, Any]
|
The consumed message's headers. |
required |
Returns:
| Type | Description |
|---|---|
Any | None
|
Any | None: An OpenTelemetry |
Any | None
|
extra is missing or the message carries no |
inject_context
¶
Add the current trace context and request id to headers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
headers
|
dict[str, Any]
|
Headers being assembled for a publish. Mutated in place and returned, for the caller's convenience. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: The same mapping. Unchanged when no trace is |
dict[str, Any]
|
active and no request id is set, so a publish outside a request |
dict[str, Any]
|
carries no empty headers. |
PublishResult
¶
Transport-specific confirmation returned by publish (or None).
Each FastStream transport returns its own confirmation type (AMQP
ConfirmationFrameType | None, Kafka RecordMetadata or future,
NATS PubAck | None, Redis int | bytes).
QueuePublisher
¶
Bases: Protocol
Minimal surface of a publisher from :meth:MessageBroker.publisher.
publish
¶
publish(message: object, /, **kwargs: Any) -> Awaitable[PublishResult]
Publish message through the bound channel.
Publisher
¶
Publisher(
broker: MessageBroker,
*,
channel: str | QueueSpec | None = None,
schema: type | None = None,
**options: Any,
)
Bases: Generic[MessageT]
Base class for class-based publishers, bound to one channel.
Subclass it with the channel and the payload model, then obtain an
instance from
:meth:~tempest_fastapi_sdk.queue.MessageBroker.publisher_for. The
constructor form works too, for a channel only known at runtime::
orders = Publisher[OrderPaid](
mq, channel="orders.paid", schema=OrderPaid,
)
Nothing is inferred from the class name — same rule as
:class:~tempest_fastapi_sdk.queue.Consumer.
Attributes:
| Name | Type | Description |
|---|---|---|
channel |
str | QueueSpec | None
|
The destination. A
:class: |
schema |
type | None
|
The payload model. When set, :meth: |
Bind this publisher to a broker.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
broker
|
MessageBroker
|
The facade to publish through. |
required |
channel
|
str | QueueSpec | None
|
Overrides the class attribute. Required when the class does not declare one. |
None
|
schema
|
type | None
|
Overrides the class attribute. |
None
|
**options
|
Any
|
Default publish options merged into every
:meth: |
{}
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When neither the class nor the constructor names a channel, since there would be nowhere to publish to. |
publish
async
¶
publish(
message: MessageT, *, key: str | bytes | None = None, **options: Any
) -> PublishResult
Publish message to this publisher's channel.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
MessageT
|
The payload. Validated against
:attr: |
required |
key
|
str | bytes | None
|
Kafka record key, exactly as
:meth: |
None
|
**options
|
Any
|
Extra publish options for this message, overriding the defaults given to the constructor. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
PublishResult |
PublishResult
|
Whatever the transport's publish returns. |
Raises:
| Type | Description |
|---|---|
TypeError
|
When :attr: |
RuntimeError
|
When the broker is not connected. |
UnsupportedTopologyError
|
When |
Subscription
dataclass
¶
Subscription(
channel: str | QueueSpec,
handler: Callable[..., Awaitable[Any]],
schema: type | None,
options: dict[str, Any],
prefetch: int | None = None,
ack_policy: AckPolicy | None = None,
group_id: str | None = None,
auto_offset_reset: OffsetResetEnum | str | None = None,
)
One channel → handler binding produced by a :class:Consumer.
Attributes:
| Name | Type | Description |
|---|---|---|
channel |
str | QueueSpec
|
The channel to subscribe on, or the spec declaring it. |
handler |
Callable[..., Awaitable[Any]]
|
The async callable that receives each decoded message. |
schema |
type | None
|
Explicit payload model. When set, it drives
decoding regardless of the handler's annotation; when |
options |
dict[str, Any]
|
Extra transport-specific subscriber options. |
prefetch |
int | None
|
Per-consumer unacknowledged-message cap,
kept apart from :attr: |
ack_policy |
AckPolicy | None
|
The ack policy asked for, resolved
by :meth: |
group_id |
str | None
|
The Kafka consumer group asked for. |
auto_offset_reset |
OffsetResetEnum | str | None
|
Where that group starts without a committed offset. |
QueueSpec
dataclass
¶
QueueSpec(
name: str,
durable: bool = True,
dead_letter: DeadLetterSpec | None = None,
message_ttl_ms: int | None = None,
max_priority: int | None = None,
max_length: int | None = None,
queue_type: QueueTypeEnum = CLASSIC,
binding: ExchangeBinding | None = None,
)
A channel plus the topology it needs.
Accepted anywhere a channel string is, so adopting it is per-channel rather than all-or-nothing.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
The channel name. The only required field, and the only one every transport understands. |
durable |
bool
|
Whether the queue survives a broker restart.
|
dead_letter |
DeadLetterSpec | None
|
Where rejected messages go. |
message_ttl_ms |
int | None
|
Discard (or dead-letter) a message after this many milliseconds. |
max_priority |
int | None
|
Enable a priority queue with this many
levels. Incompatible with :attr: |
max_length |
int | None
|
Cap the queue at this many messages;
overflow is dead-lettered when :attr: |
queue_type |
QueueTypeEnum
|
Classic or quorum. |
binding |
ExchangeBinding | None
|
Bind the queue to an exchange
under a routing key, so it receives its own copy of what is
published there. |
consumer
classmethod
¶
consumer(
consumer: str,
channel: str,
*,
exchange: ExchangeSpec | str,
dead_letter_exchange: str | None = None,
queue_type: QueueTypeEnum = CLASSIC,
) -> QueueSpec
Build one consumer's queue for an event published to exchange.
The fan-out shape: every module that reacts to channel gets
its own durable queue, <consumer>.<channel>, bound to the
shared exchange under channel — so each receives a copy
instead of competing for one.
With dead_letter_exchange, a rejected message is routed there
under the queue name (not the event key, which every consumer
shares) into <consumer>.<channel>.dlq, and both are declared
before the subscribers start. Replay it with
:meth:~tempest_fastapi_sdk.queue.MessageBroker.replay_dead_letters,
which returns it to this queue only.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
consumer
|
str
|
The consuming module, e.g. |
required |
channel
|
str
|
The event's routing key, e.g.
|
required |
exchange
|
ExchangeSpec | str
|
The exchange the event is published to. A bare name is a durable topic exchange. |
required |
dead_letter_exchange
|
str | None
|
Exchange rejected messages
go to, or |
None
|
queue_type
|
QueueTypeEnum
|
Classic or quorum. |
CLASSIC
|
Returns:
| Name | Type | Description |
|---|---|---|
QueueSpec |
QueueSpec
|
The spec to pass to |
QueueSpec
|
meth: |
DeadLetterSpec
dataclass
¶
Where a rejected message goes.
On RabbitMQ, dead-lettering is a property of the queue, not of
the consumer: the broker routes a message to exchange when it is
rejected without requeue, expires, or overflows the queue length.
Without it, a rejected message is discarded — which is the default
and is silent.
Naming a :attr:queue makes the topology complete: the exchange
and that queue are declared and bound before any subscriber
starts, so a message rejected on the first delivery already has
somewhere to go. Leave it None when something else consumes the
exchange — the delayed-retry chain of
:func:~tempest_fastapi_sdk.queue.retry_queues is the case: its
retry queue is bound there, and a second queue under the same key
would receive a duplicate of every failure.
Attributes:
| Name | Type | Description |
|---|---|---|
exchange |
str
|
The exchange rejected messages are published to.
Declared by
:meth: |
routing_key |
str | None
|
Routing key to use when dead-lettering.
|
queue |
str | None
|
The dead-letter queue to declare and bind to
:attr: |
ExchangeSpec
dataclass
¶
ExchangeSpec(name: str, kind: ExchangeKindEnum = TOPIC, durable: bool = True)
An exchange to publish to or bind a queue to.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
The exchange name. |
kind |
ExchangeKindEnum
|
The exchange type. |
durable |
bool
|
Whether it survives a broker restart. |
ExchangeBinding
dataclass
¶
ExchangeBinding(exchange: ExchangeSpec, routing_key: str)
Bind a queue to an exchange under a routing key.
This is what turns one published event into one copy per consumer: each consumer's queue is bound to the same exchange with the same key, and the broker delivers to every bound queue. Without a binding, two consumers subscribing to the same queue name share one queue and split the messages between them instead.
Attributes:
| Name | Type | Description |
|---|---|---|
exchange |
ExchangeSpec
|
The exchange to bind to. Declared when the subscriber starts. |
routing_key |
str
|
The key (a pattern, on a topic exchange) the queue receives. |
ExchangeKindEnum
¶
Bases: BaseStrEnum
AMQP exchange type.
Mirrors faststream.rabbit.ExchangeType value for value, so the
topology module imports nothing from FastStream and stays importable
without the [queue] extra.
Attributes:
| Name | Type | Description |
|---|---|---|
TOPIC |
Routes by pattern ( |
|
DIRECT |
Routes by exact key. |
|
FANOUT |
Ignores the key; every bound queue gets a copy. |
|
HEADERS |
Routes by message headers. |
OffsetResetEnum
¶
Bases: BaseStrEnum
Where a Kafka consumer group starts when it has no committed offset.
Only read when the group has never committed on a partition (a new group, or offsets expired by the broker's retention). A group that committed resumes from its commit whatever this says.
Attributes:
| Name | Type | Description |
|---|---|---|
LATEST |
Start at the end — only records written after the consumer joined are read. Kafka's and FastStream's default, and the reason a brand-new consumer misses everything that was published before its first deploy. |
|
EARLIEST |
Start at the oldest record the topic still retains. |
|
NONE |
Refuse to start without a committed offset. |
QueueTypeEnum
¶
Bases: BaseStrEnum
RabbitMQ queue implementation.
Attributes:
| Name | Type | Description |
|---|---|---|
CLASSIC |
The default. One queue master, mirrored only if a policy says so. |
|
QUORUM |
Raft-replicated across nodes. Survives the loss of a node
without the message loss classic mirroring can suffer, at the
cost of memory and of not supporting |
TransportEnum
¶
Bases: BaseStrEnum
Which broker a :class:QueueSpec is being translated for.
Detected from the FastStream broker class rather than recorded at
construction, so a :class:~tempest_fastapi_sdk.queue.MessageBroker
built by injecting a broker directly is classified the same way as
one built through a transport constructor.
UnsupportedTopologyError
¶
Bases: RuntimeError
A :class:QueueSpec asks for something the transport cannot do.
Raised where the queue is bound — :meth:~MessageBroker.on,
:meth:~MessageBroker.publisher, :meth:~MessageBroker.register —
which is startup, not per message, so the mismatch surfaces on the
first run rather than as a queue that quietly lacks the property you
declared. :meth:~MessageBroker.publish only reads the name, since
the topology belongs to the declaration and not to the message.
ConsumerRetryPolicy
dataclass
¶
ConsumerRetryPolicy(
max_attempts: int = DEFAULT_MAX_ATTEMPTS, delay_ms: int = DEFAULT_RETRY_DELAY_MS
)
How many times to retry a failing consumer, and how long to wait.
Attributes:
| Name | Type | Description |
|---|---|---|
max_attempts |
int
|
Total deliveries, including the first. |
delay_ms |
int
|
Milliseconds a message waits before being offered again. |
RetryTopology
dataclass
¶
RetryTopology(
main: QueueSpec,
retry: QueueSpec,
dead: QueueSpec,
channel: str,
main_exchange: str,
retry_exchange: str,
dead_exchange: str,
)
The three queues a retried channel needs.
Carries the exchange names as well as the queues, because the queues
alone are not a working topology: each has to be bound to its
exchange, and a chain declared without the bindings routes a rejected
message into an exchange with nothing behind it — where RabbitMQ
silently drops it. See
:meth:~tempest_fastapi_sdk.queue.MessageBroker.declare_retry_topology.
Attributes:
| Name | Type | Description |
|---|---|---|
main |
QueueSpec
|
What the consumer subscribes to. Dead-letters to the retry exchange when the handler rejects. |
retry |
QueueSpec
|
The waiting room. Holds nothing but a TTL; when a message expires it is dead-lettered back to the main exchange, which is what makes the delay work without a plugin. |
dead |
QueueSpec
|
Terminal. Nothing routes out of it — it is read by a human, or by the admin panel. |
channel |
str
|
The routing key every binding uses. |
main_exchange |
str
|
Exchange the main queue is bound to. |
retry_exchange |
str
|
Exchange the retry queue is bound to. |
dead_exchange |
str
|
Exchange the dead queue is bound to. |
retry_queues
¶
retry_queues(
channel: str,
policy: ConsumerRetryPolicy | None = None,
*,
retry_exchange: str,
main_exchange: str,
dead_exchange: str,
queue_type: QueueTypeEnum = CLASSIC,
) -> RetryTopology
Build the delayed-retry topology for channel.
RabbitMQ has no per-message delay of its own. The portable way to get
one is a pair of queues: the main queue dead-letters a rejected
message into a retry queue whose only job is to hold it, and that
queue's TTL dead-letters it back to the main exchange when it
expires. The message therefore reappears at the consumer delay_ms
later, with the broker doing the waiting — so a worker restart in the
meantime changes nothing.
The alternative is the rabbitmq_delayed_message_exchange plugin,
which is simpler to declare and requires the plugin installed —
not available on several managed offerings, including the free
CloudAMQP tier. This builds on stock AMQP instead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
channel
|
str
|
The channel the consumer subscribes to. |
required |
policy
|
ConsumerRetryPolicy | None
|
Attempts and delay. Defaults
to :class: |
None
|
retry_exchange
|
str
|
Exchange the main queue dead-letters to. |
required |
main_exchange
|
str
|
Exchange the retry queue returns messages
to. Must route back to |
required |
dead_exchange
|
str
|
Exchange the terminal queue is fed from. |
required |
queue_type
|
QueueTypeEnum
|
Queue implementation for all three. |
CLASSIC
|
Returns:
| Name | Type | Description |
|---|---|---|
RetryTopology |
RetryTopology
|
The three specs, ready to declare and subscribe. |
Notes
max_attempts is not enforced by this topology — AMQP
counts redeliveries in the x-death header but will not stop
on its own. The count is enforced by the consumer middleware
(:func:make_dead_letter_middleware), which reads that header
and routes to the dead queue once the budget is spent. Declaring
the topology without installing the middleware yields infinite
retries, which is why they are documented together.
delivery_attempt
¶
Return which delivery this is, counting from 1.
RabbitMQ records every dead-lettering in the message's x-death
header, so the number of times a message has already been rejected is
readable without any state of our own — which matters, because a
consumer restart must not reset the budget.
Entries whose reason is "expired" are skipped, and that is
load-bearing rather than a detail. RabbitMQ keeps one entry per
(queue, reason) pair, and the delayed-retry chain dead-letters a
message twice per round: once out of the main queue (rejected)
and once out of the retry queue when its TTL fires (expired).
Summing every entry therefore advanced the counter by two per retry,
so a max_attempts=3 policy gave up after two deliveries. An
expiry is the waiting room emptying itself, not a delivery that
failed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
object
|
The FastStream message being consumed. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
|
int
|
on. Falls back to |
|
int
|
so an unreadable header costs an extra attempt rather than |
|
int
|
dropping the message early. |
QueueMetrics
¶
Prometheus counters and durations for consumed messages.
Mirrors :class:~tempest_fastapi_sdk.tasks.TaskMetrics so the event
path and the task path graph the same way, on the same registry and
the same /metrics endpoint:
queue_messages_total{channel,status}—statusisok,error, orduplicatefor a delivery :meth:~tempest_fastapi_sdk.queue.MessageBroker.deduplicaterejected because a sibling worker held the claim. Its own label keeps a normal dedup outcome out of the error rate an alert reads.queue_message_duration_seconds{channel}— handler wall time.
Without this, the consumer failure rate is invisible: the message is rejected, the broker discards or dead-letters it, and nothing counts.
Register the two collectors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
registry
|
CollectorRegistry | None
|
Registry to register on.
|
None
|
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
middleware
¶
Build the FastStream middleware that feeds these collectors.
Returns:
| Type | Description |
|---|---|
type[BaseMiddleware]
|
type[BaseMiddleware]: A |
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
DedupStore
¶
Bases: Protocol
Where processed message ids are remembered.
Three operations, because two-phase marking needs them. :meth:claim
must be atomic — two workers claiming the same id concurrently
must not both receive :attr:DedupStateEnum.NEW, which is why it is one
call rather than a get followed by a set.
claim
async
¶
claim(key: str, *, ttl_seconds: int) -> DedupStateEnum
Mark key in-flight if it is unseen, and report what it was.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The message id. |
required |
ttl_seconds
|
int
|
How long the mark lives. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
DedupStateEnum |
DedupStateEnum
|
What the store held before this call. |
complete
async
¶
Mark key as successfully processed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The message id. |
required |
ttl_seconds
|
int
|
How long to remember it. |
required |
release
async
¶
Forget key so a later delivery processes it again.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The message id. |
required |
DedupStateEnum
¶
Bases: BaseStrEnum
What the store knew about a message id when it was claimed.
Attributes:
| Name | Type | Description |
|---|---|---|
NEW |
Never seen. The handler runs. |
|
IN_FLIGHT |
Another delivery of the same id is being processed. The
handler does not run and the message is rejected, so the
retry topology offers it again later — by which time the
other worker has either finished ( |
|
DONE |
Already processed successfully. The handler does not run and the message is acknowledged. |
MemoryDedupStore
dataclass
¶
In-process :class:DedupStore, for one replica and for tests.
Correct only while a single process consumes the channel — two
replicas each keep their own table and neither sees the other's
claims, so a redelivery routed to the sibling runs the handler again.
Use :class:RedisDedupStore for anything with more than one worker.
Attributes:
| Name | Type | Description |
|---|---|---|
entries |
MutableMapping[str, tuple[str, float]]
|
Key to
|
claim
async
¶
claim(key: str, *, ttl_seconds: int) -> DedupStateEnum
Claim key, reporting what the store already held.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The message id. |
required |
ttl_seconds
|
int
|
How long the mark lives. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
DedupStateEnum |
DedupStateEnum
|
The prior state. |
complete
async
¶
Mark key done.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The message id. |
required |
ttl_seconds
|
int
|
How long to remember it. |
required |
release
async
¶
Drop key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The message id. |
required |
RedisDedupStore
¶
:class:DedupStore backed by an async redis client.
:meth:claim is a single SET key in_flight NX EX ttl, so the
atomicity two-phase marking depends on comes from Redis rather than
from a lock of our own — two workers racing on the same id cannot
both be told NEW.
Wrap a Redis client.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
Any
|
An async |
required |
prefix
|
str
|
Key namespace, so dedup keys never collide with the application's own. |
'tempest:dedup:'
|
claim
async
¶
claim(key: str, *, ttl_seconds: int) -> DedupStateEnum
Claim key atomically via SET NX.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The message id. |
required |
ttl_seconds
|
int
|
How long the mark lives. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
DedupStateEnum |
DedupStateEnum
|
The prior state. A lost race reads the current |
DedupStateEnum
|
value to tell |
|
DedupStateEnum
|
between the two calls reads as |
|
DedupStateEnum
|
message rather than running it twice — the safer way to be |
|
DedupStateEnum
|
wrong for a handler that is not free to repeat. |
complete
async
¶
Mark key done.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The message id. |
required |
ttl_seconds
|
int
|
How long to remember it. |
required |
release
async
¶
Drop key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The message id. |
required |
ConcurrentDeliveryError
¶
Bases: RuntimeError
The same message id is already being processed elsewhere.
Raised so the broker rejects the duplicate rather than acknowledging it. Acknowledging would be the dangerous choice: the in-flight worker may still fail, and the copy that could have retried would be gone.
consume_span
¶
Span around one consumed message, linked to the publishing trace.
Follows the OpenTelemetry messaging semantic conventions:
messaging.system, messaging.destination.name and
messaging.operation, with the span named "<channel> process".
The publishing trace is attached as a link, not as a parent. The convention recommends it for asynchronous consumption, and the reason is practical: a consumer can run minutes after the publish, and a child span of that duration would stretch the request's trace and make its latency unreadable. A link keeps both traces truthful and still lets you jump between them.
Restores the publisher's request id for the duration of the block, so
the worker's log lines carry the id of the request that caused them —
which is worth more than the span to anyone debugging with grep.
Prepare a span for a message on channel.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
channel
|
str
|
The queue/topic the message arrived on. |
required |
headers
|
dict[str, Any] | None
|
The message headers, read for the trace context and the request id. |
None
|
inject_context
¶
Add the current trace context and request id to headers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
headers
|
dict[str, Any]
|
Headers being assembled for a publish. Mutated in place and returned, for the caller's convenience. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: The same mapping. Unchanged when no trace is |
dict[str, Any]
|
active and no request id is set, so a publish outside a request |
dict[str, Any]
|
carries no empty headers. |
extract_context
¶
Recover the publishing trace context from headers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
headers
|
dict[str, Any]
|
The consumed message's headers. |
required |
Returns:
| Type | Description |
|---|---|
Any | None
|
Any | None: An OpenTelemetry |
Any | None
|
extra is missing or the message carries no |