API reference — Transports

Nuvora.Nexus.Relay.Messaging

Core messaging abstractions and interfaces for Nuvora Nexus

dotnet add package Nuvora.Nexus.Relay.Messaging

Nuvora.Nexus.Relay.Messaging.ClaimCheck

ClaimCheckMessageBroker

public sealed class ClaimCheckMessageBroker : IMessageBroker

IMessageBroker decorator that offloads oversized payloads to an IClaimCheckStore before publishing: the body is replaced with an empty stub and a RelayMessageHeaders.ClaimCheck pointer header is attached. The consumer’s rehydrate filter restores the original payload. Payloads under the threshold pass through untouched.

Constructors

ClaimCheckMessageBroker(IMessageBroker inner, IClaimCheckStore store, ClaimCheckOptions options)

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

ClaimCheckOptions

public sealed class ClaimCheckOptions

Tuning for claim-check payload offloading.

Properties

bool DeleteOnConsume { get; set; }

Delete the offloaded payload after a successful consume. Default false: under at-least-once delivery a redelivery must still be able to rehydrate, so cleanup is normally left to a TTL/maintenance sweep of the store rather than deleting eagerly.

long ThresholdBytes { get; set; }

Payloads larger than this many bytes (UTF-8) are offloaded to the store. Default 256 KiB.

ClaimCheckPayload

public sealed record ClaimCheckPayload : IEquatable<ClaimCheckPayload>

An offloaded payload retrieved from an IClaimCheckStore.

Constructors

ClaimCheckPayload(byte[] Payload, string ContentType)

An offloaded payload retrieved from an IClaimCheckStore.

Properties

byte[] Payload { get; init; }
string ContentType { get; init; }

ClaimCheckRehydrateFilter

public sealed class ClaimCheckRehydrateFilter : IConsumeFilter

Consume filter (outermost) that restores a claim-checked payload before the handler runs: if the message carries a RelayMessageHeaders.ClaimCheck pointer, the original body is fetched from the store and put back on the message. Runs before every other filter so downstream code sees the full payload. Optionally deletes the stored payload after a successful consume.

Constructors

ClaimCheckRehydrateFilter(IClaimCheckStore store, ClaimCheckOptions options)

Properties

int Order { get; }

Relative order; lower runs first (outermost). Built-ins: kill switch (0), rate limiter (10), circuit breaker (20), concurrency limiter (30).

Methods

Task InvokeAsync(IConsumeContext context, Func<Task> next)

Invoke the filter, calling next to continue to the next filter / the handler.

IClaimCheckStore

public interface IClaimCheckStore

Stores large message payloads out-of-band so only a small pointer travels through the broker (“claim-check” pattern). The default is in-memory; a durable backend (e.g. Postgres, S3) is registered in its place for production.

Methods

Task DeleteAsync(string pointer, CancellationToken cancellationToken = default(CancellationToken))

Deletes a stored payload. No-op if the pointer is unknown.

Task<ClaimCheckPayload?> RetrieveAsync(string pointer, CancellationToken cancellationToken = default(CancellationToken))

Retrieves a previously stored payload, or null if the pointer is unknown.

Task<string> StoreAsync(byte[] payload, string contentType, CancellationToken cancellationToken = default(CancellationToken))

Stores payload and returns an opaque pointer used to retrieve it.

InMemoryClaimCheckStore

public sealed class InMemoryClaimCheckStore : IClaimCheckStore

In-memory IClaimCheckStore (default). Suitable for tests and single-process use; production deployments register a durable store instead. Payloads are not bounded — rely on ClaimCheckOptions.DeleteOnConsume or a durable backend for cleanup.

Methods

Task DeleteAsync(string pointer, CancellationToken cancellationToken = default(CancellationToken))

Deletes a stored payload. No-op if the pointer is unknown.

Task<ClaimCheckPayload?> RetrieveAsync(string pointer, CancellationToken cancellationToken = default(CancellationToken))

Retrieves a previously stored payload, or null if the pointer is unknown.

Task<string> StoreAsync(byte[] payload, string contentType, CancellationToken cancellationToken = default(CancellationToken))

Stores payload and returns an opaque pointer used to retrieve it.

Nuvora.Nexus.Relay.Messaging.Consume

CircuitBreakerConsumeFilter

public sealed class CircuitBreakerConsumeFilter : IConsumeFilter

Built-in filter (order 20): guards the handler with an ICircuitBreaker. While the circuit is open, deliveries are shed as backpressure (retried after retryAfter) so a failing downstream is not hammered. Handler outcomes are reported to the breaker — but a MessageBackpressureException raised by an inner filter (e.g. the concurrency limiter) is not counted as a downstream failure, so backpressure never trips the breaker; the entered call is abandoned instead (ICircuitBreaker.AbandonProbe), so a shed half-open probe releases its slot rather than leaving the circuit waiting forever on an outcome that will never arrive.

Constructors

CircuitBreakerConsumeFilter(ICircuitBreaker circuitBreaker, TimeSpan? retryAfter = null)

Properties

int Order { get; }

Relative order; lower runs first (outermost). Built-ins: kill switch (0), rate limiter (10), circuit breaker (20), concurrency limiter (30).

Methods

Task InvokeAsync(IConsumeContext context, Func<Task> next)

Invoke the filter, calling next to continue to the next filter / the handler.

ConcurrencyLimiterConsumeFilter

public sealed class ConcurrencyLimiterConsumeFilter : IConsumeFilter

Innermost built-in filter (order 30): caps concurrent handler executions via an IConcurrencyLimiter. When the limit is reached the delivery is shed as backpressure (retried after retryAfter) rather than queued, so the transport stays responsive and the downstream is never over-driven. The lease is released when the handler completes.

Constructors

ConcurrencyLimiterConsumeFilter(IConcurrencyLimiter concurrencyLimiter, TimeSpan? retryAfter = null)

Properties

int Order { get; }

Relative order; lower runs first (outermost). Built-ins: kill switch (0), rate limiter (10), circuit breaker (20), concurrency limiter (30).

Methods

Task InvokeAsync(IConsumeContext context, Func<Task> next)

Invoke the filter, calling next to continue to the next filter / the handler.

ConsumeContext

public sealed class ConsumeContext : IConsumeContext

Default IConsumeContext created per delivery by a transport.

Constructors

ConsumeContext(MessageBrokerMessage message, string queueName, int deliveryAttempt, CancellationToken cancellationToken)

Properties

CancellationToken CancellationToken { get; }

Token observing consumer shutdown for this delivery.

IDictionary<string, object?> Items { get; }

Per-delivery scratch state shared across filters and the handler.

MessageBrokerMessage Message { get; }

The message being delivered.

int DeliveryAttempt { get; }

1-based delivery attempt (1 on first delivery).

string QueueName { get; }

The queue the message arrived on.

ConsumePipeline

public sealed class ConsumePipeline

Composes ordered IConsumeFilters around a terminal handler. Built once (filters are sorted by IConsumeFilter.Order) and reused for every delivery. With no filters this is a transparent passthrough that simply invokes the handler.

Constructors

ConsumePipeline(IEnumerable<IConsumeFilter>? filters)

Properties

int Count { get; }

Number of filters in the pipeline (0 = passthrough).

Methods

Task ExecuteAsync(IConsumeContext context, Func<Task> handler)

Runs the filter chain, finishing with handler.

IConsumeContext

public interface IConsumeContext

Per-delivery context flowing through the IConsumeFilter pipeline that wraps the inbox handler. IConsumeContext.Items is a scratch bag for filters to pass data to one another (and to the handler) for the lifetime of a single delivery.

Properties

CancellationToken CancellationToken { get; }

Token observing consumer shutdown for this delivery.

IDictionary<string, object?> Items { get; }

Per-delivery scratch state shared across filters and the handler.

MessageBrokerMessage Message { get; }

The message being delivered.

int DeliveryAttempt { get; }

1-based delivery attempt (1 on first delivery).

string QueueName { get; }

The queue the message arrived on.

IConsumeFilter

public interface IConsumeFilter

Middleware around the inbox handler for a single delivery. Filters run in ascending IConsumeFilter.Order; each either calls next to continue the pipeline (optionally before/after doing its own work) or short-circuits by not calling it (or by throwing — which routes into the transport’s failure handling / error policy). Implementations are typically singletons and must be thread-safe.

Properties

int Order { get; }

Relative order; lower runs first (outermost). Built-ins: kill switch (0), rate limiter (10), circuit breaker (20), concurrency limiter (30).

Methods

Task InvokeAsync(IConsumeContext context, Func<Task> next)

Invoke the filter, calling next to continue to the next filter / the handler.

IConsumerRedeliveryScheduler

public interface IConsumerRedeliveryScheduler

Bridges a message consumer to the durable scheduler for scheduled (“second-level”) redelivery: when a handler asks to retry after a delay (ErrorOutcome.RetryAfter), the consumer stages a future-dated copy of the message via this abstraction and acks the original, so the delay is honored durably (surviving a process restart) instead of hot-looping a requeue.

Defined here in Messaging (which the RabbitMQ transport references) but implemented in the scheduling package (which references this assembly transitively) so the transport does not take a direct dependency on the scheduler. When no implementation is registered the consumer falls back to its default immediate republish-with-attempt-header behavior, so this is purely additive/opt-in.

Methods

Task ScheduleAsync(MessageBrokerMessage message, string queueName, TimeSpan delay, CancellationToken cancellationToken = default(CancellationToken))

Durably schedule message for re-publication to queueName’s routing after delay. Implementations stage the row inside their own transaction and commit before the caller acks the original delivery (schedule-commit-then-ack), so a crash in the window only causes an at-least-once duplicate the inbox deduplicates.

IKillSwitch

public interface IKillSwitch

An operator-controlled switch that pauses message processing. While engaged, the kill-switch consume filter sheds every delivery as backpressure (so, paired with the scheduled-redelivery scheduler, messages are deferred rather than hot-looped) until it is disengaged. Implementations are thread-safe.

Properties

bool IsEngaged { get; }

true while processing is paused.

Methods

void Disengage()

Resumes processing.

void Engage()

Pauses processing.

KillSwitch

public sealed class KillSwitch : IKillSwitch

Default in-memory IKillSwitch (a thread-safe flag).

Properties

bool IsEngaged { get; }

true while processing is paused.

Methods

void Disengage()

Resumes processing.

void Engage()

Pauses processing.

KillSwitchConsumeFilter

public sealed class KillSwitchConsumeFilter : IConsumeFilter

Outermost built-in filter (order 0): while the IKillSwitch is engaged, sheds every delivery as backpressure so the handler never runs. Paired with the scheduled-redelivery scheduler, shed messages are deferred (not hot-looped) until the switch is disengaged.

Constructors

KillSwitchConsumeFilter(IKillSwitch killSwitch)

Properties

int Order { get; }

Relative order; lower runs first (outermost). Built-ins: kill switch (0), rate limiter (10), circuit breaker (20), concurrency limiter (30).

Methods

Task InvokeAsync(IConsumeContext context, Func<Task> next)

Invoke the filter, calling next to continue to the next filter / the handler.

MessageBackpressureException

public sealed class MessageBackpressureException : Exception

Thrown by a built-in consume filter (rate limiter, circuit breaker, concurrency limiter, kill switch) to short-circuit a delivery before the handler runs because the system is shedding load — the message was not processed and should be tried again later. The transport maps this to a delayed redelivery (via the scheduled-redelivery scheduler when registered, so it does not hot-loop) rather than to the poison-message / dead-letter path, since backpressure is infrastructure state, not an application error. MessageBackpressureException.RetryAfter is an optional hint for how long to wait before retrying.

Constructors

MessageBackpressureException(string filter, string message, TimeSpan? retryAfter = null)

Properties

TimeSpan? RetryAfter { get; }

Suggested delay before the message is retried, or null to let the transport choose.

string Filter { get; }

The filter that applied backpressure (e.g. rate_limiter) — used as a telemetry tag.

RateLimiterConsumeFilter

public sealed class RateLimiterConsumeFilter : IConsumeFilter

Built-in filter (order 10): caps the consume rate via an IRateLimiter. When the rate budget is exhausted the delivery is shed as backpressure (retried after retryAfter) instead of being processed now.

Constructors

RateLimiterConsumeFilter(IRateLimiter rateLimiter, TimeSpan? retryAfter = null)

Properties

int Order { get; }

Relative order; lower runs first (outermost). Built-ins: kill switch (0), rate limiter (10), circuit breaker (20), concurrency limiter (30).

Methods

Task InvokeAsync(IConsumeContext context, Func<Task> next)

Invoke the filter, calling next to continue to the next filter / the handler.

Nuvora.Nexus.Relay.Messaging.Core

IDeadLetterQueueReplayer

public interface IDeadLetterQueueReplayer

Operational recovery for broker-side dead-letter queues: moves messages from a queue’s DLQ back to the original queue (with their delivery-attempt budget reset) so they are reprocessed after the underlying defect is fixed. Implementations must be safe to call while consumers are running.

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.

IInboxRepository

public interface IInboxRepository

Deduplication store for the inbox pattern. A processed-message row is staged on the command’s DbContext and committed in the same transaction as the handler’s effects, so a message is applied exactly once even though delivery is at-least-once: if the handler/commit fails no row is written and the redelivered message is processed again; once committed, the row makes any redelivery a no-op.

Methods

Task MarkProcessedAsync(Guid messageId, string messageType, CancellationToken cancellationToken = default(CancellationToken))

Stages a processed-message row (flushed by the unit of work’s commit).

Task<bool> HasProcessedAsync(Guid messageId, CancellationToken cancellationToken = default(CancellationToken))

True if this message was already processed (and should be skipped).

Task<int> DeleteProcessedBeforeAsync(DateTimeOffset olderThan, CancellationToken cancellationToken = default(CancellationToken))

Deletes dedup rows processed before olderThan (maintenance/retention). Executes immediately in its own statement rather than staging, and is safe to run concurrently from multiple instances (the delete is idempotent). Keep the retention window longer than the broker’s maximum redelivery delay so a late redelivery is still deduplicated.

IListenerControl

public interface IListenerControl

Operator control over message listeners: pause (stop consuming, let in-flight drain), resume, and restart (force a fresh subscription). The default implementation is in-process; listeners cooperate by registering and observing the pause signal.

Methods

IReadOnlyList<ListenerInfo> List()
bool Drain(string name)
bool Pause(string name)
bool Restart(string name)
bool Resume(string name)

IListenerRegistration

public interface IListenerRegistration

Per-listener registration handle used by the hosting listener (the inbox processor).

Properties

bool PauseRequested { get; }

True when a pause/drain was requested for this listener.

Methods

CancellationToken BeginRun(CancellationToken stoppingToken)

Begin a run cycle: returns a token cancelled when pause/restart is requested (linked to stoppingToken).

Task WaitUntilResumedAsync(CancellationToken stoppingToken)

Completes when the listener is resumed (or the host is stopping).

void ReportState(ListenerState state)

Report the listener’s current state to the control plane.

IListenerRegistry

public interface IListenerRegistry : IListenerControl

Registration surface used by listeners to enrol with the control.

Methods

IListenerRegistration Register(string name, string queueName, IReadOnlyList<string> routingKeys, string transport)

IMessageBroker

public interface IMessageBroker

Abstraction for publishing messages to message brokers (Azure Service Bus, RabbitMQ, etc.)

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

IMessageConsumer

public interface IMessageConsumer

Consumer side of the broker abstraction. Subscribes a durable queue to one or more routing keys and invokes handler per delivered message. The implementation acknowledges the message only after the handler completes successfully; if the handler throws, the message is negatively acknowledged and redelivered (at-least-once) — idempotency is the consumer’s job (see the inbox).

Methods

Task SubscribeAsync(string queueName, IReadOnlyCollection<string> routingKeys, Func<MessageBrokerMessage, CancellationToken, Task> handler, CancellationToken cancellationToken = default(CancellationToken))

IMessageConsumerLifecycle

public interface IMessageConsumerLifecycle

Optional capability of an IMessageConsumer: transports that can detect that an active subscription died (channel-level error, broker-cancelled consumer, connection loss) expose it here so the hosting service can resubscribe instead of consuming silently stopping. Implementations complete IMessageConsumerLifecycle.SubscriptionClosed when the underlying transport subscription is no longer delivering messages, and install a fresh (pending) task on the next successful IMessageConsumer.SubscribeAsync. Consumers that cannot observe transport death simply don’t implement this interface and callers fall back to passive waiting.

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.

ITransportCapabilities

public interface ITransportCapabilities

Declares the capabilities a concrete transport supports, so cross-cutting code and future transports can negotiate behaviour instead of silently diverging from the AMQP-shaped SPI (IMessageConsumer.SubscribeAsync with a queue + routing keys).

This is the seam that lets log/stream brokers (Kafka, SQS/SNS) join the model honestly: such a transport advertises ITransportCapabilities.DetectsUnroutableMessages = false and ITransportCapabilities.DeliveryModel = TransportDeliveryModel.Poll rather than pretending to match RabbitMQ semantics. A transport registers an implementation (typically the TransportCapabilities record) as a singleton in its AddRelayXxx extension.

Properties

TransportDeliveryModel DeliveryModel { get; }

How the transport delivers messages.

bool DetectsUnroutableMessages { get; }

True if a publish that matches no binding surfaces as UnroutableMessageException. RabbitMQ and the in-memory transport do; SNS/Kafka publishes to a subject with no subscribers silently succeed, so they report false.

bool SupportsConsumerLifecycle { get; }

True if the consumer implements IMessageConsumerLifecycle and signals subscription death so an owner can resubscribe (push transports). Poll transports typically leave it unimplemented, which is allowed.

bool SupportsNativeScheduling { get; }

True if the broker can natively delay/schedule a redelivery (e.g. Azure Service Bus scheduled enqueue, NATS nak-with-delay). When false, delayed redelivery is driven by the Relay IConsumerRedeliveryScheduler instead.

InMemoryListenerControl

public sealed class InMemoryListenerControl : IListenerRegistry

In-memory, thread-safe listener control (single process). Default registration.

Methods

IListenerRegistration Register(string name, string queueName, IReadOnlyList<string> routingKeys, string transport)
IReadOnlyList<ListenerInfo> List()
bool Drain(string name)
bool Pause(string name)
bool Restart(string name)
bool Resume(string name)

ListenerInfo

public sealed record ListenerInfo : IEquatable<ListenerInfo>

A listener as the management plane sees it.

Constructors

ListenerInfo(string Name, string QueueName, IReadOnlyList<string> RoutingKeys, string Transport, ListenerState State)

A listener as the management plane sees it.

Properties

IReadOnlyList<string> RoutingKeys { get; init; }

Routing keys / topics bound to the queue.

ListenerState State { get; init; }

Current run state.

string Name { get; init; }

Stable listener name (the queue name).

string QueueName { get; init; }

Broker queue the listener consumes.

string Transport { get; init; }

Transport name (e.g. “RabbitMq”).

ListenerState

public enum ListenerState

Operator-visible run state of a message listener (inbox consumer subscription).

Values

  • Starting
  • Running
  • Paused
  • Draining
  • Faulted
  • Stopped

MessageBrokerMessage

public class MessageBrokerMessage

Wrapper for messages published to message brokers

Properties

DateTimeOffset OccurredAt { get; set; }

When the event occurred

Dictionary<string, string> Headers { get; set; }

Additional headers/metadata for the message

Guid EventId { get; set; }

The event identifier from the integration event

Guid MessageId { get; set; }

Unique identifier for the message

Guid? CausationId { get; set; }

Causation ID for tracing

Guid? CorrelationId { get; set; }

Correlation ID for tracing

string EventType { get; set; }

Fully qualified type name of the event

string Payload { get; set; }

Serialized JSON payload of the event

string? Topic { get; set; }

Topic or queue name to publish to (optional, may be derived from EventType)

MessageBrokerOptions

public class MessageBrokerOptions

Configuration options for message brokers

Properties

bool AutoCreateTopics { get; set; }

Whether to automatically create topics/queues if they don’t exist

int MaxConcurrentPublishes { get; set; }

Maximum number of publishes in flight at once (the broker channel-pool size). Each in-flight publish uses its own channel; raising this pipelines publisher-confirm round-trips.

int MaxIdleChannels { get; set; }

Maximum idle channels retained in the publisher pool; channels returned beyond this are disposed.

int MaxRetries { get; set; }

Maximum number of retries for failed message publishing

int PublishConfirmTimeoutSeconds { get; set; }

Upper bound on a single publish + publisher-confirm round trip. Prevents an unresponsive broker from indefinitely stalling all publish slots.

int RetryBaseDelaySeconds { get; set; }

Base delay in seconds for exponential backoff retries

int RetryMaxDelaySeconds { get; set; }

Maximum delay in seconds for exponential backoff retries

string? TopicPrefix { get; set; }

Default topic/queue name prefix

TransportCapabilities

public sealed record TransportCapabilities : ITransportCapabilities, IEquatable<TransportCapabilities>

Immutable, declarative ITransportCapabilities. Defaults describe a RabbitMQ-style push broker (unroutable detection on, native scheduling off, lifecycle on); a transport overrides only the properties that differ.

Properties

TransportDeliveryModel DeliveryModel { get; init; }

How the transport delivers messages.

bool DetectsUnroutableMessages { get; init; }

True if a publish that matches no binding surfaces as UnroutableMessageException. RabbitMQ and the in-memory transport do; SNS/Kafka publishes to a subject with no subscribers silently succeed, so they report false.

bool SupportsConsumerLifecycle { get; init; }

True if the consumer implements IMessageConsumerLifecycle and signals subscription death so an owner can resubscribe (push transports). Poll transports typically leave it unimplemented, which is allowed.

bool SupportsNativeScheduling { get; init; }

True if the broker can natively delay/schedule a redelivery (e.g. Azure Service Bus scheduled enqueue, NATS nak-with-delay). When false, delayed redelivery is driven by the Relay IConsumerRedeliveryScheduler instead.

static TransportCapabilities Default { get; }

A RabbitMQ-style push broker: detects unroutable, no native scheduling, lifecycle-aware.

TransportDeliveryModel

public enum TransportDeliveryModel

How a transport hands messages to a consumer.

Values

  • Push — The broker pushes messages to a subscribed consumer (e.g. RabbitMQ, in-memory).
  • Poll — The consumer pulls/long-polls for messages (e.g. SQS, Kafka offset reads).

UnroutableMessageException

public sealed class UnroutableMessageException : Exception

Thrown when the broker accepted a publish but could not route the message to any queue (e.g. the exchange has no matching binding). The message was not delivered anywhere, so callers must treat the publish as failed — the outbox records the failure and retries/dead-letters instead of marking the message processed.

Constructors

UnroutableMessageException(string message)
UnroutableMessageException(string message, Exception innerException)

Nuvora.Nexus.Relay.Messaging.DependencyInjection

ClaimCheckServiceCollectionExtensions

public static class ClaimCheckServiceCollectionExtensions

Registration helper for claim-check payload offloading.

Methods

static IServiceCollection AddRelayClaimCheck(this IServiceCollection services, Action<ClaimCheckOptions>? configure = null)

Enables claim-check offloading: decorates the registered IMessageBroker to offload oversized payloads and adds the rehydrate consume filter. Uses the in-memory store unless a durable IClaimCheckStore is already registered. Call after the broker (e.g. AddRelayRabbitMq).

ConsumeFilterServiceCollectionExtensions

public static class ConsumeFilterServiceCollectionExtensions

Registration helpers for the built-in consume filters that wrap the inbox handler. Each is opt-in and additive — registering none leaves the consume pipeline a transparent passthrough. Filters compose by IConsumeFilter.Order: kill switch (0) → rate limiter (10) → circuit breaker (20) → concurrency limiter (30). On backpressure they throw MessageBackpressureException, which the transport maps to a delayed redelivery (pair with AddRelayConsumerRedelivery so shed messages are deferred rather than hot-looped).

Methods

static IServiceCollection AddRelayConsumeCircuitBreaker(this IServiceCollection services, Action<CircuitBreakerOptions> configure)

Adds the circuit-breaker filter backed by a CircuitBreaker.

static IServiceCollection AddRelayConsumeConcurrencyLimiter(this IServiceCollection services, int maxConcurrency, TimeSpan? retryAfter = null)

Adds the concurrency-limiter filter capping concurrent handler executions at maxConcurrency.

static IServiceCollection AddRelayConsumeKillSwitch(this IServiceCollection services)

Adds the kill-switch filter and a default IKillSwitch (resolve it to engage/disengage).

static IServiceCollection AddRelayConsumeRateLimiter(this IServiceCollection services, Action<RateLimiterOptions> configure)

Adds the rate-limiter filter backed by a TokenBucketRateLimiter.

MessageErrorPolicyServiceCollectionExtensions

public static class MessageErrorPolicyServiceCollectionExtensions

Registration helper for the per-exception message error policy.

Methods

static IServiceCollection AddRelayMessageErrorPolicy(this IServiceCollection services, Action<MessageErrorPolicyOptions> configure)

Registers a RuleBasedMessageErrorPolicy built from configure as the singleton IMessageErrorPolicy. Transports consult it on a handler failure; without it (the default) they keep their existing retry-then-dead-letter behavior.

PartitioningServiceCollectionExtensions

public static class PartitioningServiceCollectionExtensions

Registration helpers for sticky (partitioned) processing.

Methods

static IServiceCollection AddRelayPartitionPublishing(this IServiceCollection services, Action<PartitionOptions> configure)

Enables partition-aware publishing: registers the IPartitioner and PartitionOptions, and decorates the registered IMessageBroker so a message carrying the x-relay-partition-key header is routed to its partition queue. Call after the broker (e.g. AddRelayRabbitMq). The consuming side (the PartitionCoordinator) is started by the host with the inbox handler.

Nuvora.Nexus.Relay.Messaging.Errors

ErrorDisposition

public enum ErrorDisposition

What a transport should do with a delivery whose handler threw, as decided by an IMessageErrorPolicy.

Values

  • Retry — Retry the delivery. The transport default is the republish-with-attempt-header pattern (back of the queue, attempt count incremented, dead-lettered once the attempt cap is reached); an ErrorOutcome.RetryDelay requests scheduled (second-level) redelivery.
  • Requeue — Requeue immediately (nack, requeue=true) — back to the head of the queue without advancing the attempt count. Use for transient backpressure (e.g. a tripped circuit breaker) where the work should be re-attempted promptly rather than counted as a poison-message attempt.
  • DeadLetter — Dead-letter immediately (nack, requeue=false), skipping the remaining delivery attempts. Routes via the queue’s dead-letter exchange when configured.
  • Ignore — Treat as handled and drop the message (ack). Use for exceptions that are safe to swallow.

ErrorOutcome

public readonly record struct ErrorOutcome : IEquatable<ErrorOutcome>

The action an IMessageErrorPolicy chose for a failed delivery: a disposition and, for ErrorDisposition.Retry, an optional delay requesting scheduled redelivery.

Constructors

ErrorOutcome(ErrorDisposition Disposition, TimeSpan? RetryDelay = null)

The action an IMessageErrorPolicy chose for a failed delivery: a disposition and, for ErrorDisposition.Retry, an optional delay requesting scheduled redelivery.

Properties

ErrorDisposition Disposition { get; init; }
TimeSpan? RetryDelay { get; init; }

Methods

static ErrorOutcome RetryAfter(TimeSpan delay)

Retry after delay (scheduled / second-level redelivery).

Fields

static readonly ErrorOutcome DeadLetter

Dead-letter immediately.

static readonly ErrorOutcome Ignore

Ack and drop the message.

static readonly ErrorOutcome Requeue

Requeue immediately without advancing the attempt count.

static readonly ErrorOutcome Retry

Retry via the transport default (republish-with-attempt-header, no extra delay).

IMessageErrorPolicy

public interface IMessageErrorPolicy

Decides, per exception, how a transport should handle a delivery whose handler threw. Lets an application route different failures differently — ignore a known-benign exception, dead-letter a non-retryable one immediately, requeue on transient backpressure, or fall back to the default retry-then-dead-letter flow. When no policy is registered (or IMessageErrorPolicy.Evaluate returns null) the transport keeps its default behavior, so this is purely additive. Implementations must be thread-safe.

Methods

ErrorOutcome? Evaluate(Exception exception, MessageErrorContext context)

Returns the disposition for exception, or null to defer to the transport’s default handling (republish-with-attempt-header, dead-lettering at the cap).

MessageErrorContext

public readonly record struct MessageErrorContext : IEquatable<MessageErrorContext>

Context handed to an IMessageErrorPolicy for a failed delivery: the message, the queue it arrived on, and the 1-based delivery attempt that just failed.

Constructors

MessageErrorContext(MessageBrokerMessage Message, string QueueName, int DeliveryAttempt)

Context handed to an IMessageErrorPolicy for a failed delivery: the message, the queue it arrived on, and the 1-based delivery attempt that just failed.

Properties

MessageBrokerMessage Message { get; init; }
int DeliveryAttempt { get; init; }
string QueueName { get; init; }

MessageErrorPolicyOptions

public sealed class MessageErrorPolicyOptions

Fluent, ordered rule set for RuleBasedMessageErrorPolicy: the first rule whose predicate matches the thrown exception wins. Exception matches are assignable-from (a rule for a base type also matches its subclasses), so register the most specific rules first.

Methods

MessageErrorPolicyOptions DeadLetter<TException>()

Dead-letters TException (and subclasses) immediately.

MessageErrorPolicyOptions Ignore<TException>()

Acks and drops TException (and subclasses).

MessageErrorPolicyOptions On<TException>(ErrorDisposition disposition, TimeSpan? retryDelay = null)

Maps TException (and subclasses) to disposition.

MessageErrorPolicyOptions Requeue<TException>()

Requeues TException (and subclasses) immediately.

MessageErrorPolicyOptions RetryAfter<TException>(TimeSpan delay)

Schedules a delayed retry for TException (and subclasses).

MessageErrorPolicyOptions When(Func<Exception, bool> predicate, ErrorOutcome outcome)

Adds a custom predicate rule resolving to outcome.

RuleBasedMessageErrorPolicy

public sealed class RuleBasedMessageErrorPolicy : IMessageErrorPolicy

The built-in IMessageErrorPolicy: evaluates the ordered rules in MessageErrorPolicyOptions (first match wins) and returns null when none match, so unmatched exceptions keep the transport’s default handling.

Constructors

RuleBasedMessageErrorPolicy(MessageErrorPolicyOptions options)

Methods

ErrorOutcome? Evaluate(Exception exception, MessageErrorContext context)

Returns the disposition for exception, or null to defer to the transport’s default handling (republish-with-attempt-header, dead-lettering at the cap).

Nuvora.Nexus.Relay.Messaging.Partitioning

PartitionCoordinator

public sealed class PartitionCoordinator : IAsyncDisposable

Owns a subset of a partition group’s partitions and consumes only those. For each partition it contends for the partition:{group}:{n} session-scoped IDistributedLock; whoever holds the lock runs a consumer on that partition’s queue, so each partition has a single owner and is processed in order. The lock is held on a dedicated connection that dies with the process, so a crashed owner’s partitions are picked up by another node on its next reconciliation tick (failover).

A transient subscription death (channel/connection blip) while the lock is still held triggers a resubscribe on the same lock; ownership is only relinquished on PartitionCoordinator.StopAsync/dispose.

Start it with PartitionCoordinator.StartAsync and stop it with PartitionCoordinator.StopAsync (or dispose). It is deliberately not an IHostedService so this transport package takes no hosting dependency; a host wires it to the inbox handler and drives its lifetime.

Constructors

PartitionCoordinator(PartitionOptions options, IDistributedLock distributedLock, Func<IMessageConsumer> consumerFactory, Func<MessageBrokerMessage, CancellationToken, Task> handler, ILogger<PartitionCoordinator> logger, TimeSpan? reconcileInterval = null)

Properties

IReadOnlyCollection<int> OwnedPartitions { get; }

Partitions currently owned by this node.

Methods

Task StartAsync(CancellationToken cancellationToken = default(CancellationToken))

Starts the reconciliation loop; returns once the first reconciliation has run.

Task StopAsync()
ValueTask DisposeAsync()

Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources asynchronously.

PartitionTopology

public static class PartitionTopology

Naming for partitioned topology. Each partition has its own durable queue bound to the shared exchange with a partition-specific routing key, so a publisher can address one partition and a single owning consumer drains it in order. Queue and routing key share the same {group}.p{n} form.

Methods

static string LockResource(string group, int partition)

Ownership-lock resource name for partition partition of group.

static string QueueName(string group, int partition)

Queue (and routing key) for partition partition of group.

static string RoutingKey(string group, int partition)

Routing key a publisher stamps to address partition partition.

PartitionedMessageBroker

public sealed class PartitionedMessageBroker : IMessageBroker

Decorates an IMessageBroker to route partitioned messages: when a message carries the RelayMessageHeaders.PartitionKey header, its topic is rewritten to the owning partition’s routing key ({group}.p{n}) so it lands on that partition’s queue. Messages without a partition key pass through unchanged.

Constructors

PartitionedMessageBroker(IMessageBroker inner, IPartitioner partitioner, PartitionOptions options)

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