API reference — Transports
Nuvora.Nexus.Relay.Messaging.RabbitMq
RabbitMQ message broker for Nuvora Nexus Relay
dotnet add package Nuvora.Nexus.Relay.Messaging.RabbitMq
Nuvora.Nexus.Relay.Messaging.RabbitMq
RabbitMqDeadLetterReplayer
public sealed class RabbitMqDeadLetterReplayer : IDeadLetterQueueReplayer
IDeadLetterQueueReplayer for RabbitMQ: pulls messages off <queue>.dlq with basic.get and republishes them to the original queue via the default exchange, with the x-relay-delivery-attempts header reset so the replayed message gets a fresh retry budget. The channel has publisher confirms enabled and each DLQ copy is acked only after its replacement publish is confirmed — a crash mid-replay therefore duplicates (deduplicated by the consumer inbox) instead of losing the message. Opens a short-lived connection per call: replay is a rare operator action, not a hot path.
Constructors
RabbitMqDeadLetterReplayer(IOptions<RabbitMqOptions> options, ILogger<RabbitMqDeadLetterReplayer> logger)
Methods
Task<int> ReplayAsync(string queueName, int maxMessages = 100, CancellationToken cancellationToken = default(CancellationToken))
Replays up to maxMessages messages from queueName’s dead-letter queue back onto queueName. Each message is re-enqueued (confirmed by the broker) before its DLQ copy is acknowledged, so a crash mid-replay duplicates rather than loses — duplicates are absorbed by the consumer’s inbox dedup. Returns the number replayed.
RabbitMqMessageBroker
public sealed class RabbitMqMessageBroker : IMessageBroker, IAsyncDisposable
IMessageBroker over RabbitMQ (client v7, async API). Publishes to a durable topic exchange with publisher confirms enabled, so a publish only completes once the broker has accepted (and persisted) the message — a failed publish throws and lets the outbox record the failure rather than silently dropping the event. Publishes are mandatory: a message the broker cannot route to any queue (no matching binding) is returned via basic.return and surfaces as an UnroutableMessageException instead of being silently dropped. The v7 client correlates returns with confirms (the return frame precedes the ack and faults the publish task with PublishException); as a defence in depth each pooled channel also registers a IChannel.BasicReturnAsync handler that records returned message ids, and the id is checked after the confirm completes — the channel dispatches inbound frames in order, so the return handler has run by the time the confirm resolves. Channels are not safe for concurrent use, so each in-flight publish rents its own channel from a small pool (bounded by MessageBrokerOptions.MaxConcurrentPublishes); idle channels are reused, broken ones discarded. Durable retry/dead-lettering is owned by the outbox, so this performs only a short in-call retry for transient connection blips. Unroutable messages are not retried in-call (the topology won’t fix itself within milliseconds) — the outbox backoff owns that retry.
Constructors
RabbitMqMessageBroker(IOptions<RabbitMqOptions> options, ILogger<RabbitMqMessageBroker> logger)
Methods
Task PublishAsync(MessageBrokerMessage message, CancellationToken cancellationToken = default(CancellationToken))
Publish a message to the message broker
Task PublishManyAsync(IEnumerable<MessageBrokerMessage> messages, CancellationToken cancellationToken = default(CancellationToken))
Publish multiple messages to the message broker
Task<bool> PingAsync(CancellationToken cancellationToken = default(CancellationToken))
Health probe: ensures the shared publisher connection is open, establishing it if necessary. Returns true when the broker is reachable; throws on connection failure (callers — the health check — translate that into an unhealthy result with the exception preserved).
ValueTask DisposeAsync()
Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources asynchronously.
RabbitMqMessageConsumer
public sealed class RabbitMqMessageConsumer : IMessageConsumer, IMessageConsumerLifecycle, IAsyncDisposable
IMessageConsumer over RabbitMQ (client v7, async API). Declares a durable queue bound to the shared topic exchange and consumes with manual acknowledgement: a message is acked only after the handler succeeds — so combined with the inbox it yields exactly-once processing on top of at-least-once delivery.
Poison messages / dead-lettering. By default the queue is declared with a dead-letter exchange (RabbitMqOptions.DeadLetterExchange, default <exchange>.dlx) and a companion <queue>.dlq queue. When the handler throws, delivery attempts are tracked with the republish-with-attempt-header pattern (header x-relay-delivery-attempts): the message is republished to the back of the queue with the count incremented and the original is acked. This was chosen over x-death inspection because a basic.nack(requeue=true) does not increment x-death, and requeueing to the back also avoids hot-looping on the same message at the head of the queue. Once RabbitMqOptions.MaxDeliveryAttempts is reached the message is nacked without requeue, which routes it to the DLQ via the queue’s x-dead-letter-exchange argument.
Migration note. Adding queue arguments to a queue that already exists without them fails with PRECONDITION_FAILED. That failure is caught: a clear warning is logged and the subscription is retried without the dead-letter arguments (legacy requeue behaviour) so a pre-existing deployment keeps working. To adopt the DLQ on such a queue, delete/migrate the queue (or set RabbitMqOptions.EnableDeadLettering to false to silence the warning).
Subscription lifecycle. Implements IMessageConsumerLifecycle: channel shutdown and broker-side consumer cancellation complete RabbitMqMessageConsumer.SubscriptionClosed so the hosting service (the inbox processor) can resubscribe. The connection factory disables topology recovery for this consumer — resubscription owns consumer recovery deterministically instead of racing the client’s automatic topology recovery (which could duplicate consumers).
Foreign messages. Messages published by other stacks may carry no parseable MessageId/event-id. To keep inbox deduplication effective, a stable fallback id is derived as the first 16 bytes of SHA-256 over the routing key and body, so every redelivery of the same message maps to the same id (instead of a fresh Guid per delivery).
Constructors
RabbitMqMessageConsumer(IOptions<RabbitMqOptions> options, ILogger<RabbitMqMessageConsumer> logger, IMessageErrorPolicy? errorPolicy = null, IEnumerable<IConsumeFilter>? consumeFilters = null, IConsumerRedeliveryScheduler? redeliveryScheduler = null)
Properties
Task SubscriptionClosed { get; }
Completes when an active subscription dies. Callers should re-grab this property after every resubscribe — the task instance is replaced on each successful subscribe.
Methods
Task SubscribeAsync(string queueName, IReadOnlyCollection<string> routingKeys, Func<MessageBrokerMessage, CancellationToken, Task> handler, CancellationToken cancellationToken = default(CancellationToken))
ValueTask DisposeAsync()
Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources asynchronously.
RabbitMqOptions
public sealed class RabbitMqOptions : MessageBrokerOptions
Connection and topology options for the RabbitMQ broker.
Properties
RabbitMqSslOptions Ssl { get; set; }
TLS settings for the broker connection.
bool EnableDeadLettering { get; set; }
Whether consumer queues are declared with a dead-letter exchange and a companion <queue>.dlq queue, and whether poison messages (handler keeps failing) are routed there after RabbitMqOptions.MaxDeliveryAttempts instead of being requeued forever. Disabling this restores the legacy requeue-forever behaviour.
int ConsumerChannels { get; set; }
Number of independent consumer channels opened per subscription. A RabbitMQ v7 IChannel is not safe for concurrent use, so true concurrent processing comes from running several channels — each with its own consumer (ack/nack serialized per channel) — off the one connection. The default of 1 preserves today’s single-channel behavior; raise it to process deliveries concurrently. Composes with the concurrency-limiter consume filter (which caps total in-flight handlers regardless of channel count).
int MaxDeliveryAttempts { get; set; }
Maximum number of delivery attempts for a message whose handler keeps throwing before it is routed to the dead-letter queue (only effective while dead-lettering is active).
int Port { get; set; }
int RequestedHeartbeatSeconds { get; set; }
Heartbeat interval (seconds) negotiated with the broker; detects half-open TCP connections. Values <= 0 fall back to the client default.
string ExchangeName { get; set; }
Durable topic exchange events are published to.
string ExchangeType { get; set; }
Exchange type (topic by default).
string HostName { get; set; }
string Password { get; set; }
string UserName { get; set; }
string VirtualHost { get; set; }
string? ClientProvidedName { get; set; }
Connection name shown in the RabbitMQ management UI (e.g. the service name); the publisher and consumer connections are suffixed to stay distinguishable.
string? DeadLetterExchange { get; set; }
Name of the dead-letter exchange. Defaults to "<ExchangeName>.dlx" when null/empty.
ushort PrefetchCount { get; set; }
Consumer prefetch (QoS): how many unacknowledged deliveries the broker pushes to a consumer channel at once. Bounds memory under a slow handler. Divided across RabbitMqOptions.ConsumerChannels (each channel gets max(1, PrefetchCount / ConsumerChannels)).
RabbitMqSslOptions
public sealed class RabbitMqSslOptions
TLS options for the RabbitMQ connection.
Properties
SslPolicyErrors AcceptablePolicyErrors { get; set; }
Certificate validation errors that are tolerated (default: none). Loosen only for development/self-signed setups.
bool Enabled { get; set; }
Whether TLS is used for the broker connection.
string? ServerName { get; set; }
Expected server name (CN/SAN) on the broker’s certificate. Defaults to RabbitMqOptions.HostName when not set.
Nuvora.Nexus.Relay.Messaging.RabbitMq.DependencyInjection
RabbitMqServiceCollectionExtensions
public static class RabbitMqServiceCollectionExtensions
Registration helpers for the RabbitMQ message broker.
Methods
static IServiceCollection AddRelayRabbitMq(this IServiceCollection services, Action<RabbitMqOptions> configure)
Nuvora.Nexus.Relay.Messaging.RabbitMq.HealthChecks
RabbitMqHealthCheck
public sealed class RabbitMqHealthCheck : IHealthCheck
Health check for broker connectivity: pings the shared publisher connection (establishing it when needed) with a bounded timeout, so a dead or unreachable RabbitMQ surfaces as Unhealthy instead of only as outbox publish failures minutes later.
Constructors
RabbitMqHealthCheck(IMessageBroker broker)
Methods
Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default(CancellationToken))
Runs the health check, returning the status of the component being checked.
RabbitMqHealthCheckBuilderExtensions
public static class RabbitMqHealthCheckBuilderExtensions
Health-check registration for the RabbitMQ broker connection.
Methods
static IHealthChecksBuilder AddRelayRabbitMq(this IHealthChecksBuilder builder, string name = "relay-rabbitmq", IEnumerable<string>? tags = null)
Adds the RabbitMQ connectivity health check (pings the shared publisher connection with a 5s bound). Wire it into the readiness endpoint: services.AddHealthChecks().AddRelayRabbitMq().