Class InboxProcessor
Provides the core implementation of the inbox pattern for reliable message processing with effectively-once processing. Delivery remains at-least-once and handlers must be idempotent. This processor coordinates between message storage, deduplication tracking, and the message dispatching infrastructure.
[SuppressMessage("Maintainability", "CA1506:Avoid excessive class coupling", Justification = "Core coordinator that legitimately orchestrates message processing through multiple subsystems")]
public sealed class InboxProcessor : IInboxProcessor, IAsyncDisposable
- Inheritance
-
InboxProcessor
- Implements
- Inherited Members
Remarks
The InboxProcessor implements a producer-consumer pattern where messages are loaded from persistent storage in batches and processed through the message pipeline. It provides configurable batching, parallel processing, retry handling, and comprehensive metrics collection. The processor is designed for high-throughput scenarios while maintaining reliability and observability requirements of enterprise messaging systems.
CA1506 suppressed: InboxProcessor is a core coordinator that legitimately orchestrates message processing through multiple subsystems (batching, telemetry, persistence, scheduling, error handling, serialization). High coupling is inherent to its coordination responsibilities and cannot be reduced without fragmenting cohesive functionality.
Constructors
InboxProcessor(IOptions<InboxOptions>, IInboxStore, IServiceProvider, DispatchJsonSerializer, ILogger<InboxProcessor>, ITransportCircuitBreakerRegistry, IBinaryEnvelopeDeserializer?, IDeadLetterQueue?, IBackoffCalculator?, IOptions<DeliveryGuaranteeOptions>?, IDeduplicationStore?, IPayloadSerializer?)
Initializes a new instance of the InboxProcessor class with the specified dependencies and configuration options for message. processing operations.
public InboxProcessor(IOptions<InboxOptions> options, IInboxStore inboxStore, IServiceProvider serviceProvider, DispatchJsonSerializer serializer, ILogger<InboxProcessor> logger, ITransportCircuitBreakerRegistry circuitBreakerRegistry, IBinaryEnvelopeDeserializer? envelopeDeserializer = null, IDeadLetterQueue? deadLetterQueue = null, IBackoffCalculator? backoffCalculator = null, IOptions<DeliveryGuaranteeOptions>? deliveryGuaranteeOptions = null, IDeduplicationStore? deduplicationStore = null, IPayloadSerializer? payloadSerializer = null)
Parameters
optionsIOptions<InboxOptions>Configuration options controlling inbox processing behavior and performance characteristics.
inboxStoreIInboxStoreThe storage service for persistent inbox message operations.
serviceProviderIServiceProviderService provider for dependency injection and handler activation.
serializerDispatchJsonSerializerJSON serializer for message serialization and deserialization operations.
loggerILogger<InboxProcessor>Logger for diagnostic and operational messaging.
circuitBreakerRegistryITransportCircuitBreakerRegistryRequired circuit breaker registry for message-type resilience. It is required rather than optional because a drain that silently ran without a circuit breaker was indistinguishable from one that had a working breaker, and the difference only became visible under a failing transport.
envelopeDeserializerIBinaryEnvelopeDeserializerOptional binary envelope deserializer for high-performance binary envelope support.
deadLetterQueueIDeadLetterQueueExplicit dead letter queue for failed messages. Null is rejected; pass NullDeadLetterQueue.Instance to intentionally discard.
backoffCalculatorIBackoffCalculatorOptional backoff calculator for retry delays. Uses ExponentialBackoffCalculator if not provided.
deliveryGuaranteeOptionsIOptions<DeliveryGuaranteeOptions>Optional delivery guarantee options. Uses default at-least-once semantics if not provided.
deduplicationStoreIDeduplicationStoreOptional deduplication store for exactly-once message processing. When provided, duplicate messages are skipped.
payloadSerializerIPayloadSerializerOptional pluggable payload serializer. Must be the same one the inbox writes through: a payload it wrote names its serializer in a leading magic byte and is read back through that serializer, so a binary format such as MessagePack or Protobuf drains as written rather than being handed to the JSON reader. Entries written before one was configured are raw JSON and keep the JSON path.
Remarks
The constructor validates configuration options and initializes internal components including the message queue, batch processing metrics, and dynamic batch sizing calculator if enabled. Queue capacity must be at least as large as the producer batch size to ensure proper operation.
Exceptions
- ArgumentNullException
Thrown when any required parameter is null.
- InvalidOperationException
Thrown when configuration options are invalid or inconsistent.
Methods
DispatchPendingMessagesAsync(CancellationToken)
Asynchronously processes all pending messages in the inbox using a producer-consumer pattern, ensuring effectively-once processing (a redelivered message is skipped, not reprocessed) and proper error handling throughout the operation.
public Task<int> DispatchPendingMessagesAsync(CancellationToken cancellationToken)
Parameters
cancellationTokenCancellationTokenToken to monitor for cancellation requests during processing.
Returns
- Task<int>
A task representing the asynchronous operation, containing the total number of messages successfully processed during this execution.
Remarks
This method coordinates producer and consumer tasks where the producer loads messages from storage into an internal queue, and the consumer processes messages through the dispatch pipeline. Both tasks run concurrently to maximize throughput while maintaining proper resource utilization and error handling.
Exceptions
- ObjectDisposedException
Thrown if the processor has been disposed.
- InvalidOperationException
Thrown if Init has not been called before this method.
DisposeAsync()
Asynchronously releases all resources used by the InboxProcessor, including internal queues, tasks, and any disposable dependencies. This method ensures proper cleanup and resource release.
public ValueTask DisposeAsync()
Returns
- ValueTask
A ValueTask representing the asynchronous dispose operation.
Remarks
This method implements the async dispose pattern and ensures that all internal resources are properly cleaned up, including stopping any running producer/consumer tasks and disposing of queue structures and metrics collectors. The method is safe to call multiple times.
Init(string)
Initializes the inbox processor with the specified dispatcher identifier, preparing internal data structures and coordination mechanisms for message processing operations.
public void Init(string dispatcherId)
Parameters
dispatcherIdstringUnique identifier for this dispatcher instance used for coordination and tracking.
Remarks
This method must be called before DispatchPendingMessagesAsync to properly initialize the processor state. It sets up the instance-aware queue for message deduplication and coordination between producer and consumer operations.
Exceptions
- ArgumentException
Thrown when dispatcherId is null, empty, or whitespace.