Referencia Pública de API .NETL3 Persistencia e IntegracionesEstableAOT: Parcial

EricksonLopez.Outbox

High-performance, Zero-Reflection, NativeAOT-ready Transactional Outbox and Idempotent Inbox ecosystem for modern .NET (8/9/10). Solves the Dual-Write Problem with guaranteed At-Least-Once Delivery across 7 databases and 8 message broker transports.

52 namespaces225 tipos1078 miembrosGenerado desde XML docs y ensamblados · UTC 2026-12-01

Mostrando 225 de 225 tipos (1078 miembros)

EricksonLopez.Inbox#

9
interface

IIdempotencyChecker

Ensamblado: EricksonLopez.Inbox.Abstractions
public interface IIdempotencyChecker

Provides idempotency verification and execution guarantees for incoming messages.

Miembros (2)

  • methodExecuteIdempotentlyAsync
    ValueTask<bool> ExecuteIdempotentlyAsync(string messageId, string consumerName, Func<CancellationToken, ValueTask> handler, CancellationToken cancellationToken = default)

    Executes the specified handler if and only if the message has not yet been processed by `consumerName`.

    messageId: string
    The message identifier.
    consumerName: string
    The consumer or handler name.
    handler: Func<CancellationToken, ValueTask>
    The message processing delegate.
    cancellationToken: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: `true` if the message was new and executed; `false` if it was a duplicate and skipped.

  • methodHasProcessedAsync
    ValueTask<bool> HasProcessedAsync(string messageId, string consumerName, CancellationToken cancellationToken = default)

    Checks whether the message identified by `messageId` has already been processed by `consumerName`.

    messageId: string
    The message identifier.
    consumerName: string
    The consumer or handler name.
    cancellationToken: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: `true` if already processed; otherwise, `false`.

interface

IInboxConsumerFilter

Ensamblado: EricksonLopez.Inbox.Abstractions
public interface IInboxConsumerFilter

Defines the contract for consumer-side message deduplication and idempotent handler execution.

Miembros (1)

  • methodExecuteIdempotentlyAsync
    ValueTask<bool> ExecuteIdempotentlyAsync(string messageId, string consumerName, Func<CancellationToken, ValueTask> handler, CancellationToken cancellationToken = default)

    Executes the given handler if and only if the message with `messageId` has not yet been processed by `consumerName`.

    messageId: string
    The unique incoming message identifier.
    consumerName: string
    The logical consumer or handler name.
    handler: Func<CancellationToken, ValueTask>
    The message processing delegate.
    cancellationToken: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: `true` if the message was new and handled successfully; `false` if it was a duplicate and skipped.

interface

IInboxDeadLetterStore

Ensamblado: EricksonLopez.Inbox.Abstractions
public interface IInboxDeadLetterStore

Administrative store contract for inspecting, recording, replaying, purging, and measuring consumer Inbox Dead-Letter Queue (DLQ) messages.

Miembros (7)

  • methodGetByIdAsync
    ValueTask<InboxDeadLetterEntry?> GetByIdAsync(Guid id, CancellationToken cancellationToken = default)

    Retrieves a single quarantined DLQ message by its identifier.

    id: Guid
    cancellationToken: CancellationToken
  • methodGetDeadLettersAsync
    ValueTask<IReadOnlyList<InboxDeadLetterEntry>> GetDeadLettersAsync(int limit = 100, int offset = 0, string? messageType = null, CancellationToken cancellationToken = default)

    Lists quarantined DLQ messages ordered by most recent failure first.

    limit: int
    offset: int
    messageType: string?
    cancellationToken: CancellationToken
  • methodGetMetricsAsync
    ValueTask<InboxDeadLetterMetrics> GetMetricsAsync(CancellationToken cancellationToken = default)

    Computes live operational health metrics across the consumer Inbox and Dead-Letter Queue.

    cancellationToken: CancellationToken
  • methodPurgeAsync
    ValueTask<int> PurgeAsync(DateTimeOffset? failedBefore = null, string? messageType = null, CancellationToken cancellationToken = default)

    Permanently deletes quarantined DLQ messages matching optional age and message-type filters.

    failedBefore: DateTimeOffset?
    messageType: string?
    cancellationToken: CancellationToken
  • methodRecordDeadLetterAsync
    ValueTask RecordDeadLetterAsync(InboxDeadLetterEntry entry, CancellationToken cancellationToken = default)

    Quarantines a failed message in the Dead-Letter Queue.

    entry: InboxDeadLetterEntry
    cancellationToken: CancellationToken
  • methodReplayAsync
    ValueTask<bool> ReplayAsync(Guid id, CancellationToken cancellationToken = default)

    Atomically moves a quarantined DLQ message back into the active inbox for reprocessing, resetting retry state.

    id: Guid
    cancellationToken: CancellationToken
  • methodReplayBatchAsync
    ValueTask<int> ReplayBatchAsync(IReadOnlyCollection<Guid> ids, CancellationToken cancellationToken = default)

    Atomically moves a batch of quarantined DLQ messages back into the active inbox for reprocessing.

    ids: IReadOnlyCollection<Guid>
    cancellationToken: CancellationToken
interface

IInboxEntry

Ensamblado: EricksonLopez.Inbox.Abstractions
public interface IInboxEntry

Represents an entry in the consumer inbox for deduplication and idempotency tracking.

Miembros (3)

  • propertyConsumerName
    string ConsumerName { get; }

    Gets the logical name of the consumer or handler processing the message.

  • propertyMessageId
    string MessageId { get; }

    Gets the unique incoming message or event identifier.

  • propertyProcessedAt
    DateTimeOffset ProcessedAt { get; }

    Gets the timestamp when the message was processed.

interface

IInboxStore

Ensamblado: EricksonLopez.Inbox.Abstractions
public interface IInboxStore

Defines persistence operations for storing, querying, and purging consumer inbox entries.

Miembros (3)

  • methodHasBeenProcessedAsync
    ValueTask<bool> HasBeenProcessedAsync(string messageId, string consumerName, CancellationToken cancellationToken = default)

    Checks whether the message has already been processed by the specified consumer.

    messageId: string
    The message identifier.
    consumerName: string
    The consumer name.
    cancellationToken: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: `true` if already processed; otherwise, `false`.

  • methodPurgeExpiredEntriesAsync
    ValueTask PurgeExpiredEntriesAsync(DateTimeOffset olderThan, CancellationToken cancellationToken = default)

    Purges inbox entries older than the specified timestamp threshold.

    olderThan: DateTimeOffset
    The timestamp threshold; entries older than this will be purged.
    cancellationToken: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: A `ValueTask` representing the asynchronous operation.

  • methodTryRecordAsync
    ValueTask<bool> TryRecordAsync(IInboxEntry entry, CancellationToken cancellationToken = default)

    Attempts to record a processed message entry.

    entry: IInboxEntry
    The inbox entry to record.
    cancellationToken: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: A task representing the asynchronous operation. The result is `true` if the entry was newly recorded; otherwise `false` if it already exists (duplicate).

record

InboxDeadLetterEntry

Ensamblado: EricksonLopez.Inbox.Abstractions
public sealed record InboxDeadLetterEntry(Guid Id, string MessageType, string Payload, DateTimeOffset ReceivedAt, int RetryCount, DateTimeOffset FailedAt, string? Error, Guid? CompanyId, Guid? TenantId)

Represents an unprocessable consumer inbox message quarantined in the Dead-Letter Queue (DLQ).

Miembros (10)

  • constructorInboxDeadLetterEntry
    public InboxDeadLetterEntry(Guid Id, string MessageType, string Payload, DateTimeOffset ReceivedAt, int RetryCount, DateTimeOffset FailedAt, string? Error = null, Guid? CompanyId = null, Guid? TenantId = null)

    Initializes a new instance of InboxDeadLetterEntry.

    Id: Guid
    Unique message identifier.
    MessageType: string
    Logical event/command type or consumer identifier.
    Payload: string
    Serialized JSON message payload.
    ReceivedAt: DateTimeOffset
    UTC timestamp when the message originally arrived.
    RetryCount: int
    Number of failed processing attempts before quarantine.
    FailedAt: DateTimeOffset
    UTC timestamp when the message was moved to the DLQ.
    Error: string?
    Last failure diagnostic message, if available.
    CompanyId: Guid?
    Optional multi-company RLS owner identifier.
    TenantId: Guid?
    Optional multi-tenant RLS owner identifier.
  • propertyCompanyId
    public Guid? CompanyId { get; init; }

    Optional multi-company RLS owner identifier.

  • propertyError
    public string? Error { get; init; }

    Last failure diagnostic message, if available.

  • propertyFailedAt
    public DateTimeOffset FailedAt { get; init; }

    UTC timestamp when the message was moved to the DLQ.

  • propertyId
    public Guid Id { get; init; }

    Unique message identifier.

  • propertyMessageType
    public string MessageType { get; init; }

    Logical event/command type or consumer identifier.

  • propertyPayload
    public string Payload { get; init; }

    Serialized JSON message payload.

  • propertyReceivedAt
    public DateTimeOffset ReceivedAt { get; init; }

    UTC timestamp when the message originally arrived.

  • propertyRetryCount
    public int RetryCount { get; init; }

    Number of failed processing attempts before quarantine.

  • propertyTenantId
    public Guid? TenantId { get; init; }

    Optional multi-tenant RLS owner identifier.

record

InboxDeadLetterMetrics

Ensamblado: EricksonLopez.Inbox.Abstractions
public sealed record InboxDeadLetterMetrics(long DeadLetterCount, long PendingInboxCount, long FailedInboxCount, DateTimeOffset? OldestDeadLetterAt, IReadOnlyDictionary<string, long> DeadLettersByMessageType)

Aggregated operational health metrics for consumer Inbox and Dead-Letter Queue tables.

Miembros (6)

  • constructorInboxDeadLetterMetrics
    public InboxDeadLetterMetrics(long DeadLetterCount, long PendingInboxCount, long FailedInboxCount, DateTimeOffset? OldestDeadLetterAt, IReadOnlyDictionary<string, long> DeadLettersByMessageType)

    Initializes a new instance of InboxDeadLetterMetrics.

    DeadLetterCount: long
    Total quarantined entries currently in the DLQ.
    PendingInboxCount: long
    Unprocessed entries currently awaiting execution in the primary inbox.
    FailedInboxCount: long
    Primary inbox entries with `retry_count > 0` or non-null error awaiting retry.
    OldestDeadLetterAt: DateTimeOffset?
    Timestamp of the oldest quarantined DLQ message, or `null` when empty.
    DeadLettersByMessageType: IReadOnlyDictionary<string, long>
    Breakdown of quarantined DLQ entries grouped by `message_type`.
  • propertyDeadLetterCount
    public long DeadLetterCount { get; init; }

    Total quarantined entries currently in the DLQ.

  • propertyDeadLettersByMessageType
    public IReadOnlyDictionary<string, long> DeadLettersByMessageType { get; init; }

    Breakdown of quarantined DLQ entries grouped by `message_type`.

  • propertyFailedInboxCount
    public long FailedInboxCount { get; init; }

    Primary inbox entries with `retry_count > 0` or non-null error awaiting retry.

  • propertyOldestDeadLetterAt
    public DateTimeOffset? OldestDeadLetterAt { get; init; }

    Timestamp of the oldest quarantined DLQ message, or `null` when empty.

  • propertyPendingInboxCount
    public long PendingInboxCount { get; init; }

    Unprocessed entries currently awaiting execution in the primary inbox.

record

InboxEntry

Ensamblado: EricksonLopez.Inbox.Abstractions
public sealed record InboxEntry(string MessageId, string ConsumerName, DateTimeOffset ProcessedAt) : IInboxEntry
Implementa: IInboxEntry

Represents an immutable record implementing `IInboxEntry` for message deduplication and idempotency tracking.

Miembros (5)

  • constructorInboxEntry
    public InboxEntry(string MessageId, string ConsumerName, DateTimeOffset ProcessedAt)

    Initializes a new instance of InboxEntry.

    MessageId: string
    The unique incoming message or event identifier.
    ConsumerName: string
    The logical name of the consumer or handler processing the message.
    ProcessedAt: DateTimeOffset
    The timestamp when the message was processed.
  • propertyConsumerName
    public string ConsumerName { get; init; }

    The logical name of the consumer or handler processing the message.

  • propertyIsEmpty
    public bool IsEmpty { get; }

    Gets a value indicating whether this entry has no message identifier and consumer name.

  • propertyMessageId
    public string MessageId { get; init; }

    The unique incoming message or event identifier.

  • propertyProcessedAt
    public DateTimeOffset ProcessedAt { get; init; }

    The timestamp when the message was processed.

class

InboxServiceCollectionExtensions

Ensamblado: EricksonLopez.Inbox
public static class InboxServiceCollectionExtensions

Provides extension methods for `IServiceCollection` to configure the Inbox deduplication and idempotency subsystem.

Miembros (2)

  • methodAddInMemoryInbox
    public static IServiceCollection AddInMemoryInbox(this IServiceCollection services, Action<InboxOptions>? configure = null)

    Configures the Inbox to use the thread-safe `InMemoryInboxStore`.

    services: this IServiceCollection
    The service collection.
    configure: Action<InboxOptions>?
    Optional configuration action for `InboxOptions`.

    Retorna: The service collection for chaining.

    Exceptions: ArgumentNullException: `services` is `null`

  • methodAddInbox
    public static IServiceCollection AddInbox(this IServiceCollection services, Action<InboxOptions>? configure = null)

    Adds core Inbox services to the specified `IServiceCollection`.

    services: this IServiceCollection
    The service collection.
    configure: Action<InboxOptions>?
    Optional configuration action for `InboxOptions`.

    Retorna: The service collection for chaining.

    Exceptions: ArgumentNullException: `services` is `null`

EricksonLopez.Inbox.Configuration#

1
class

InboxOptions

Ensamblado: EricksonLopez.Inbox
public sealed class InboxOptions

Configuration options for the Inbox idempotency and deduplication engine.

Miembros (3)

  • propertyCleanupInterval
    public TimeSpan CleanupInterval { get; set; }

    Gets or sets the interval between background cleanup sweeps. Default is 1 hour.

  • propertyEnableAutomaticCleanup
    public bool EnableAutomaticCleanup { get; set; }

    Gets or sets whether the background cleanup service should be automatically registered and run. Default is `true`.

  • propertyRetentionPeriod
    public TimeSpan RetentionPeriod { get; set; }

    Gets or sets the duration after which processed inbox records are considered expired. Default is 7 days.

EricksonLopez.Inbox.Core#

2
class

DefaultInboxConsumerFilter

Ensamblado: EricksonLopez.Inbox
public sealed class DefaultInboxConsumerFilter : IInboxConsumerFilter
Implementa: IInboxConsumerFilter

Provides the default implementation of `IInboxConsumerFilter` backed by an `IInboxStore`.

Miembros (2)

  • constructorDefaultInboxConsumerFilter
    public DefaultInboxConsumerFilter(IInboxStore inboxStore, ILogger<DefaultInboxConsumerFilter>? logger = null, TimeProvider? timeProvider = null)

    Initializes a new instance of the `DefaultInboxConsumerFilter` class.

    inboxStore: IInboxStore
    The underlying inbox store.
    logger: ILogger<DefaultInboxConsumerFilter>?
    Optional logger instance.
    timeProvider: TimeProvider?
    Optional time provider.

    Exceptions: ArgumentNullException: `inboxStore` is `null`

  • methodExecuteIdempotentlyAsync
    public async ValueTask<bool> ExecuteIdempotentlyAsync(string messageId, string consumerName, Func<CancellationToken, ValueTask> handler, CancellationToken cancellationToken = default)

    Executes the given handler if and only if the message with `messageId` has not yet been processed by `consumerName`.

    messageId: string
    The unique incoming message identifier.
    consumerName: string
    The logical consumer or handler name.
    handler: Func<CancellationToken, ValueTask>
    The message processing delegate.
    cancellationToken: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: `true` if the message was new and handled successfully; `false` if it was a duplicate and skipped.

class

IdempotencyChecker

Ensamblado: EricksonLopez.Inbox
public sealed class IdempotencyChecker : IIdempotencyChecker
Implementa: IIdempotencyChecker

Provides the default implementation of `IIdempotencyChecker`.

Miembros (3)

  • constructorIdempotencyChecker
    public IdempotencyChecker(IInboxStore inboxStore, IInboxConsumerFilter consumerFilter)

    Initializes a new instance of the `IdempotencyChecker` class.

    inboxStore: IInboxStore
    The inbox persistence store.
    consumerFilter: IInboxConsumerFilter
    The consumer filter.

    Exceptions: ArgumentNullException: `inboxStore` or `consumerFilter` is `null`

  • methodExecuteIdempotentlyAsync
    public ValueTask<bool> ExecuteIdempotentlyAsync(string messageId, string consumerName, Func<CancellationToken, ValueTask> handler, CancellationToken cancellationToken = default)

    Executes the specified handler if and only if the message has not yet been processed by `consumerName`.

    messageId: string
    The message identifier.
    consumerName: string
    The consumer or handler name.
    handler: Func<CancellationToken, ValueTask>
    The message processing delegate.
    cancellationToken: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: `true` if the message was new and executed; `false` if it was a duplicate and skipped.

  • methodHasProcessedAsync
    public ValueTask<bool> HasProcessedAsync(string messageId, string consumerName, CancellationToken cancellationToken = default)

    Checks whether the message identified by `messageId` has already been processed by `consumerName`.

    messageId: string
    The message identifier.
    consumerName: string
    The consumer or handler name.
    cancellationToken: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: `true` if already processed; otherwise, `false`.

EricksonLopez.Inbox.Hosting#

1
class

InboxCleanupBackgroundService

Ensamblado: EricksonLopez.Inbox
public sealed class InboxCleanupBackgroundService : BackgroundService
Hereda de: BackgroundService

Provides a background service that periodically sweeps and purges expired inbox entries based on configured retention policies.

Miembros (1)

  • constructorInboxCleanupBackgroundService
    public InboxCleanupBackgroundService(IInboxStore inboxStore, IOptions<InboxOptions> options, ILogger<InboxCleanupBackgroundService>? logger = null, TimeProvider? timeProvider = null)

    Initializes a new instance of the `InboxCleanupBackgroundService` class.

    inboxStore: IInboxStore
    The inbox persistence store.
    options: IOptions<InboxOptions>
    The configured inbox options.
    logger: ILogger<InboxCleanupBackgroundService>?
    Optional logger instance.
    timeProvider: TimeProvider?
    Optional time provider.

    Exceptions: ArgumentNullException: `inboxStore` or `options` is `null`

EricksonLopez.Inbox.PostgreSql#

4
class

PostgreSqlInboxDeadLetterStore

Ensamblado: EricksonLopez.Inbox.PostgreSql
public sealed partial class PostgreSqlInboxDeadLetterStore : IInboxDeadLetterStore
Implementa: IInboxDeadLetterStore

PostgreSQL Row-Level Security (RLS)-compatible implementation of `IInboxDeadLetterStore` supporting atomic CTE replay from `inbox_dlq` back into `inbox_messages`, parameterized purge, and live queue observability metrics over either `NpgsqlDataSource` or an active `DbConnection`/`DbTransaction`.

Miembros (18)

  • constructorPostgreSqlInboxDeadLetterStore
    public PostgreSqlInboxDeadLetterStore(NpgsqlDataSource dataSource, IOptions<PostgreSqlInboxOptions>? options = null)

    Initializes a new instance of the `PostgreSqlInboxDeadLetterStore` class backed by an `NpgsqlDataSource`.

    dataSource: NpgsqlDataSource
    options: IOptions<PostgreSqlInboxOptions>?
  • constructorPostgreSqlInboxDeadLetterStore
    public PostgreSqlInboxDeadLetterStore(PostgreSqlInboxOptions options)

    Initializes a new instance of the `PostgreSqlInboxDeadLetterStore` class for explicit transactional `DbConnection` execution.

    options: PostgreSqlInboxOptions
  • methodBuildReplaySingleSql
    public string BuildReplaySingleSql()

    Gets the compiled SQL statement used to atomically replay a DLQ entry back into the active inbox.

  • methodBuildRlsDeadLetterTableDdl
    public static string BuildRlsDeadLetterTableDdl(string schema = "", string table = "")

    Generates idempotent PostgreSQL DDL for the consumer Dead-Letter Queue table with `FORCE ROW LEVEL SECURITY`.

    schema: string
    table: string
  • methodGetByIdAsync
    public async ValueTask<InboxDeadLetterEntry?> GetByIdAsync(Guid id, CancellationToken cancellationToken = default)

    Retrieves a single quarantined DLQ message by its identifier.

    id: Guid
    cancellationToken: CancellationToken
  • methodGetByIdAsync
    public async ValueTask<InboxDeadLetterEntry?> GetByIdAsync(Guid id, DbConnection connection, DbTransaction? transaction = null, CancellationToken cancellationToken = default)

    Retrieves a single quarantined DLQ message using the caller's active `DbConnection` / `DbTransaction`.

    id: Guid
    connection: DbConnection
    transaction: DbTransaction?
    cancellationToken: CancellationToken
  • methodGetDeadLettersAsync
    public async ValueTask<IReadOnlyList<InboxDeadLetterEntry>> GetDeadLettersAsync(DbConnection connection, DbTransaction? transaction = null, int limit = 100, int offset = 0, string? messageType = null, CancellationToken cancellationToken = default)

    Lists quarantined DLQ messages using the caller's active `DbConnection` / `DbTransaction`.

    connection: DbConnection
    transaction: DbTransaction?
    limit: int
    offset: int
    messageType: string?
    cancellationToken: CancellationToken
  • methodGetDeadLettersAsync
    public async ValueTask<IReadOnlyList<InboxDeadLetterEntry>> GetDeadLettersAsync(int limit = 100, int offset = 0, string? messageType = null, CancellationToken cancellationToken = default)

    Lists quarantined DLQ messages ordered by most recent failure first.

    limit: int
    offset: int
    messageType: string?
    cancellationToken: CancellationToken
  • methodGetMetricsAsync
    public async ValueTask<InboxDeadLetterMetrics> GetMetricsAsync(CancellationToken cancellationToken = default)

    Computes live operational health metrics across the consumer Inbox and Dead-Letter Queue.

    cancellationToken: CancellationToken
  • methodGetMetricsAsync
    public async ValueTask<InboxDeadLetterMetrics> GetMetricsAsync(DbConnection connection, DbTransaction? transaction = null, CancellationToken cancellationToken = default)

    Computes live operational health metrics across the consumer Inbox and Dead-Letter Queue using the caller's `DbConnection` / `DbTransaction`.

    connection: DbConnection
    transaction: DbTransaction?
    cancellationToken: CancellationToken
  • methodPurgeAsync
    public async ValueTask<int> PurgeAsync(DateTimeOffset? failedBefore = null, string? messageType = null, CancellationToken cancellationToken = default)

    Permanently deletes quarantined DLQ messages matching optional age and message-type filters.

    failedBefore: DateTimeOffset?
    messageType: string?
    cancellationToken: CancellationToken
  • methodPurgeAsync
    public async ValueTask<int> PurgeAsync(DbConnection connection, DbTransaction? transaction = null, DateTimeOffset? failedBefore = null, string? messageType = null, CancellationToken cancellationToken = default)

    Permanently deletes quarantined DLQ messages using the caller's active `DbConnection` / `DbTransaction`.

    connection: DbConnection
    transaction: DbTransaction?
    failedBefore: DateTimeOffset?
    messageType: string?
    cancellationToken: CancellationToken
  • methodRecordDeadLetterAsync
    public async ValueTask RecordDeadLetterAsync(InboxDeadLetterEntry entry, CancellationToken cancellationToken = default)

    Quarantines a failed message in the Dead-Letter Queue.

    entry: InboxDeadLetterEntry
    cancellationToken: CancellationToken
  • methodRecordDeadLetterAsync
    public async ValueTask RecordDeadLetterAsync(InboxDeadLetterEntry entry, DbConnection connection, DbTransaction? transaction = null, CancellationToken cancellationToken = default)

    Quarantines a failed message in the Dead-Letter Queue using the caller's active `DbConnection` / `DbTransaction`.

    entry: InboxDeadLetterEntry
    connection: DbConnection
    transaction: DbTransaction?
    cancellationToken: CancellationToken
  • methodReplayAsync
    public async ValueTask<bool> ReplayAsync(Guid id, CancellationToken cancellationToken = default)

    Atomically moves a quarantined DLQ message back into the active inbox for reprocessing, resetting retry state.

    id: Guid
    cancellationToken: CancellationToken
  • methodReplayAsync
    public async ValueTask<bool> ReplayAsync(Guid id, DbConnection connection, DbTransaction? transaction = null, CancellationToken cancellationToken = default)

    Atomically moves a quarantined DLQ message back into the active inbox within the caller's `DbConnection` / `DbTransaction`.

    id: Guid
    connection: DbConnection
    transaction: DbTransaction?
    cancellationToken: CancellationToken
  • methodReplayBatchAsync
    public async ValueTask<int> ReplayBatchAsync(IReadOnlyCollection<Guid> ids, CancellationToken cancellationToken = default)

    Atomically moves a batch of quarantined DLQ messages back into the active inbox for reprocessing.

    ids: IReadOnlyCollection<Guid>
    cancellationToken: CancellationToken
  • methodReplayBatchAsync
    public async ValueTask<int> ReplayBatchAsync(IReadOnlyCollection<Guid> ids, DbConnection connection, DbTransaction? transaction = null, CancellationToken cancellationToken = default)

    Atomically replays a batch of quarantined DLQ messages back into the active inbox within the caller's `DbConnection` / `DbTransaction`.

    ids: IReadOnlyCollection<Guid>
    connection: DbConnection
    transaction: DbTransaction?
    cancellationToken: CancellationToken
class

PostgreSqlInboxOptions

Ensamblado: EricksonLopez.Inbox.PostgreSql
public sealed class PostgreSqlInboxOptions

Configuration options for `PostgreSqlInboxStore` including table naming and multi-tenant / multi-company Row-Level Security (RLS) columns.

Miembros (9)

  • propertyAmbientCompanyIdResolver
    public Func<Guid?>? AmbientCompanyIdResolver { get; set; }

    Gets or sets an optional ambient company UUID resolver invoked when recording entries without an explicit company argument.

  • propertyAmbientTenantIdResolver
    public Func<Guid?>? AmbientTenantIdResolver { get; set; }

    Gets or sets an optional ambient tenant UUID resolver invoked when recording entries without an explicit tenant argument.

  • propertyCompanyColumnName
    public string CompanyColumnName { get; set; }

    Gets or sets the company column name when `EnableCompanyColumn` is enabled. Default is `company_id`.

  • propertyDeadLetterTableName
    public string DeadLetterTableName { get; set; }

    Gets or sets the consumer Dead-Letter Queue (DLQ) table name. Default is `inbox_dlq`.

  • propertyEnableCompanyColumn
    public bool EnableCompanyColumn { get; set; }

    Gets or sets whether the inbox table includes a `company_id UUID` column populated from ambient/explicit company context. Default is `false`.

  • propertyEnableTenantColumn
    public bool EnableTenantColumn { get; set; }

    Gets or sets whether the inbox table includes a `tenant_id UUID` column populated from ambient/explicit tenant context. Default is `false`.

  • propertySchemaName
    public string SchemaName { get; set; }

    Gets or sets the PostgreSQL schema containing the inbox table. Default is `public`.

  • propertyTableName
    public string TableName { get; set; }

    Gets or sets the inbox table name. Default is `inbox_messages`.

  • propertyTenantColumnName
    public string TenantColumnName { get; set; }

    Gets or sets the tenant column name when `EnableTenantColumn` is enabled. Default is `tenant_id`.

class

PostgreSqlInboxServiceCollectionExtensions

Ensamblado: EricksonLopez.Inbox.PostgreSql
public static class PostgreSqlInboxServiceCollectionExtensions

Dependency injection registration extensions for `PostgreSqlInboxStore`.

Miembros (1)

  • methodAddPostgreSqlInbox
    public static IServiceCollection AddPostgreSqlInbox(this IServiceCollection services, Action<PostgreSqlInboxOptions>? configure = null)

    Registers `PostgreSqlInboxStore` as the singleton `IInboxStore` implementation.

    services: this IServiceCollection
    The service collection.
    configure: Action<PostgreSqlInboxOptions>?
    Optional configuration delegate for `PostgreSqlInboxOptions`.

    Retorna: The service collection for chaining.

class

PostgreSqlInboxStore

Ensamblado: EricksonLopez.Inbox.PostgreSql
public sealed partial class PostgreSqlInboxStore : IInboxStore
Implementa: IInboxStore

PostgreSQL implementation of `IInboxStore` providing atomic `INSERT ... ON CONFLICT DO NOTHING` consumer idempotency deduplication with optional `tenant_id` / `company_id` Row-Level Security (RLS) column binding.

Miembros (8)

  • constructorPostgreSqlInboxStore
    public PostgreSqlInboxStore(NpgsqlDataSource dataSource, IOptions<PostgreSqlInboxOptions>? options = null)

    Initializes a new instance of the `PostgreSqlInboxStore` class backed by an `NpgsqlDataSource`.

    dataSource: NpgsqlDataSource
    The PostgreSQL data source.
    options: IOptions<PostgreSqlInboxOptions>?
    Optional inbox configuration.
  • constructorPostgreSqlInboxStore
    public PostgreSqlInboxStore(PostgreSqlInboxOptions options)

    Initializes a new instance of the `PostgreSqlInboxStore` class for explicit transactional `DbConnection` execution.

    options: PostgreSqlInboxOptions
    The inbox configuration options.
  • methodBuildRlsTableDdl
    public static string BuildRlsTableDdl(string schema = "", string table = "", bool includeTenantColumn = true, bool includeCompanyColumn = true)

    Generates idempotent PostgreSQL DDL for the consumer inbox table with `FORCE ROW LEVEL SECURITY`.

    schema: string
    table: string
    includeTenantColumn: bool
    includeCompanyColumn: bool
  • methodHasBeenProcessedAsync
    public async ValueTask<bool> HasBeenProcessedAsync(string messageId, string consumerName, CancellationToken cancellationToken = default)

    Checks whether the message has already been processed by the specified consumer.

    messageId: string
    The message identifier.
    consumerName: string
    The consumer name.
    cancellationToken: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: `true` if already processed; otherwise, `false`.

  • methodPurgeExpiredEntriesAsync
    public async ValueTask PurgeExpiredEntriesAsync(DateTimeOffset olderThan, CancellationToken cancellationToken = default)

    Purges inbox entries older than the specified timestamp threshold.

    olderThan: DateTimeOffset
    The timestamp threshold; entries older than this will be purged.
    cancellationToken: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: A `ValueTask` representing the asynchronous operation.

  • methodTryRecordAsync
    public async ValueTask<bool> TryRecordAsync(IInboxEntry entry, CancellationToken cancellationToken = default)

    Attempts to record a processed message entry.

    entry: IInboxEntry
    The inbox entry to record.
    cancellationToken: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: A task representing the asynchronous operation. The result is `true` if the entry was newly recorded; otherwise `false` if it already exists (duplicate).

  • methodTryRecordAsync
    public async ValueTask<bool> TryRecordAsync(IInboxEntry entry, DbConnection connection, DbTransaction transaction, Guid? tenantId = null, Guid? companyId = null, CancellationToken cancellationToken = default)

    Atomically records `entry` inside the caller's active `DbTransaction` using `ON CONFLICT DO NOTHING`.

    entry: IInboxEntry
    connection: DbConnection
    transaction: DbTransaction
    tenantId: Guid?
    companyId: Guid?
    cancellationToken: CancellationToken
  • propertyInsertSql
    public string InsertSql { get; }

    Gets the compiled parameterized `INSERT ... ON CONFLICT DO NOTHING` SQL statement.

EricksonLopez.Inbox.Storage#

2
class

InMemoryInboxDeadLetterStore

Ensamblado: EricksonLopez.Inbox
public sealed class InMemoryInboxDeadLetterStore : IInboxDeadLetterStore
Implementa: IInboxDeadLetterStore

Thread-safe in-memory implementation of `IInboxDeadLetterStore` for unit testing and local hosts.

Miembros (8)

  • methodGetByIdAsync
    public ValueTask<InboxDeadLetterEntry?> GetByIdAsync(Guid id, CancellationToken cancellationToken = default)

    Retrieves a single quarantined DLQ message by its identifier.

    id: Guid
    cancellationToken: CancellationToken
  • methodGetDeadLettersAsync
    public ValueTask<IReadOnlyList<InboxDeadLetterEntry>> GetDeadLettersAsync(int limit = 100, int offset = 0, string? messageType = null, CancellationToken cancellationToken = default)

    Lists quarantined DLQ messages ordered by most recent failure first.

    limit: int
    offset: int
    messageType: string?
    cancellationToken: CancellationToken
  • methodGetMetricsAsync
    public ValueTask<InboxDeadLetterMetrics> GetMetricsAsync(CancellationToken cancellationToken = default)

    Computes live operational health metrics across the consumer Inbox and Dead-Letter Queue.

    cancellationToken: CancellationToken
  • methodPurgeAsync
    public ValueTask<int> PurgeAsync(DateTimeOffset? failedBefore = null, string? messageType = null, CancellationToken cancellationToken = default)

    Permanently deletes quarantined DLQ messages matching optional age and message-type filters.

    failedBefore: DateTimeOffset?
    messageType: string?
    cancellationToken: CancellationToken
  • methodRecordDeadLetterAsync
    public ValueTask RecordDeadLetterAsync(InboxDeadLetterEntry entry, CancellationToken cancellationToken = default)

    Quarantines a failed message in the Dead-Letter Queue.

    entry: InboxDeadLetterEntry
    cancellationToken: CancellationToken
  • methodReplayAsync
    public ValueTask<bool> ReplayAsync(Guid id, CancellationToken cancellationToken = default)

    Atomically moves a quarantined DLQ message back into the active inbox for reprocessing, resetting retry state.

    id: Guid
    cancellationToken: CancellationToken
  • methodReplayBatchAsync
    public ValueTask<int> ReplayBatchAsync(IReadOnlyCollection<Guid> ids, CancellationToken cancellationToken = default)

    Atomically moves a batch of quarantined DLQ messages back into the active inbox for reprocessing.

    ids: IReadOnlyCollection<Guid>
    cancellationToken: CancellationToken
  • propertyReplayedEntries
    public IReadOnlyCollection<InboxDeadLetterEntry> ReplayedEntries { get; }

    Gets entries replayed since initialization (for test assertions).

class

InMemoryInboxStore

Ensamblado: EricksonLopez.Inbox
public sealed class InMemoryInboxStore : IInboxStore
Implementa: IInboxStore

Provides an in-memory, thread-safe implementation of `IInboxStore` suited for testing and single-node workloads.

Miembros (7)

  • constructorInMemoryInboxStore
    public InMemoryInboxStore(TimeProvider? timeProvider = null)

    Initializes a new instance of the `InMemoryInboxStore` class.

    timeProvider: TimeProvider?
    Optional time provider for testability.
  • methodClear
    public void Clear()

    Clears all entries from the store.

  • methodHasBeenProcessedAsync
    public ValueTask<bool> HasBeenProcessedAsync(string messageId, string consumerName, CancellationToken cancellationToken = default)

    Checks whether the message has already been processed by the specified consumer.

    messageId: string
    The message identifier.
    consumerName: string
    The consumer name.
    cancellationToken: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: `true` if already processed; otherwise, `false`.

  • methodPurgeExpiredEntriesAsync
    public ValueTask PurgeExpiredEntriesAsync(DateTimeOffset olderThan, CancellationToken cancellationToken = default)

    Purges inbox entries older than the specified timestamp threshold.

    olderThan: DateTimeOffset
    The timestamp threshold; entries older than this will be purged.
    cancellationToken: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: A `ValueTask` representing the asynchronous operation.

  • methodTryRecordAsync
    public ValueTask<bool> TryRecordAsync(IInboxEntry entry, CancellationToken cancellationToken = default)

    Attempts to record a processed message entry.

    entry: IInboxEntry
    The inbox entry to record.
    cancellationToken: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: A task representing the asynchronous operation. The result is `true` if the entry was newly recorded; otherwise `false` if it already exists (duplicate).

  • propertyCount
    public int Count { get; }

    Gets the count of active recorded entries in the store.

  • propertyTimeProvider
    public TimeProvider TimeProvider { get; }

    Gets the configured `TimeProvider` instance.

EricksonLopez.Outbox#

43
class

BrokerRouteBuilder

Ensamblado: EricksonLopez.Outbox
public sealed class BrokerRouteBuilder

Configures a message-type-specific route to a designated broker publisher.

Miembros (2)

  • methodToPublisher
    public OutboxOptions ToPublisher(Func<IServiceProvider, IBrokerPublisher> factory)

    Routes the specified message type to a publisher resolved via the provided factory delegate.

    factory: Func<IServiceProvider, IBrokerPublisher>
    A factory delegate that receives the `IServiceProvider` and returns the publisher to use.

    Retorna: The parent `OutboxOptions` instance for method chaining.

    Exceptions: ArgumentNullException: `factory` is `null`

  • methodToPublisher
    public OutboxOptions ToPublisher(IBrokerPublisher publisher)

    Routes the specified message type to the given singleton publisher instance.

    publisher: IBrokerPublisher
    The publisher instance to dispatch messages of the configured type to.

    Retorna: The parent `OutboxOptions` instance for method chaining.

    Exceptions: ArgumentNullException: `publisher` is `null`

class

BrokerRouteGroupBuilder

Ensamblado: EricksonLopez.Outbox
public sealed class BrokerRouteGroupBuilder

Configures multiple message-type routes to a designated broker publisher in bulk.

Miembros (2)

  • methodToPublisher
    public OutboxOptions ToPublisher(Func<IServiceProvider, IBrokerPublisher> factory)

    Routes all message types in the group to a publisher resolved via the provided factory delegate.

    factory: Func<IServiceProvider, IBrokerPublisher>
    A factory delegate that receives the `IServiceProvider` and returns the publisher to use.

    Retorna: The parent `OutboxOptions` instance for method chaining.

    Exceptions: ArgumentNullException: `factory` is `null`

  • methodToPublisher
    public OutboxOptions ToPublisher(IBrokerPublisher publisher)

    Routes all message types in the group to the given singleton publisher instance.

    publisher: IBrokerPublisher
    The publisher instance to dispatch messages to.

    Retorna: The parent `OutboxOptions` instance for method chaining.

    Exceptions: ArgumentNullException: `publisher` is `null`

record

DeadLetterMessage

Ensamblado: EricksonLopez.Outbox
public readonly record struct DeadLetterMessage(Guid Id, Guid OriginalMessageId, string MessageType, ReadOnlyMemory<byte> Payload, string? CorrelationId, string? CausationId, ReadOnlyMemory<byte> Headers, DateTimeOffset CreatedAt, DateTimeOffset DeadLetteredAt, int RetryCount, string Reason, string? LastError)

Represents a message that has exhausted all retry attempts and cannot be processed.

Notas:

Dead-lettered messages are stored in a separate table or queue for manual inspection, replay, or discard.

Miembros (14)

  • constructorDeadLetterMessage
    public DeadLetterMessage(Guid Id, Guid OriginalMessageId, string MessageType, ReadOnlyMemory<byte> Payload, string? CorrelationId, string? CausationId, ReadOnlyMemory<byte> Headers, DateTimeOffset CreatedAt, DateTimeOffset DeadLetteredAt, int RetryCount, string Reason, string? LastError)

    Initializes a new instance of DeadLetterMessage.

    Id: Guid
    The unique identifier of the dead-letter record.
    OriginalMessageId: Guid
    The unique identifier of the original outbox message.
    MessageType: string
    The stable string alias representing the message type.
    Payload: ReadOnlyMemory<byte>
    The serialized message content.
    CorrelationId: string?
    The correlation identifier for distributed tracing.
    CausationId: string?
    The causation identifier for tracking the origin of the message.
    Headers: ReadOnlyMemory<byte>
    The serialized JSON representation of custom metadata headers.
    CreatedAt: DateTimeOffset
    The date and time when the original message was stored in the outbox.
    DeadLetteredAt: DateTimeOffset
    The date and time when the message was moved to the dead-letter queue.
    RetryCount: int
    The total number of retry attempts made before the message was dead-lettered.
    Reason: string
    A brief description or code indicating the reason for dead-lettering.
    LastError: string?
    The full text or stack trace of the last error encountered during dispatch.

    Dead-lettered messages are stored in a separate table or queue for manual inspection, replay, or discard.

  • methodFromOutboxMessage
    public static DeadLetterMessage FromOutboxMessage(OutboxMessage original, int retryCount, string reason, string? lastError = null)

    Creates a `DeadLetterMessage` from an `OutboxMessage` that has exhausted its configured number of retry attempts.

    original: OutboxMessage
    The original outbox message that failed.
    retryCount: int
    The total number of retry attempts made.
    reason: string
    A brief description or reason code for the failure.
    lastError: string?
    The full text or stack trace of the last error encountered.

    Retorna: A new `DeadLetterMessage` instance representing the failed message.

  • propertyCausationId
    public string? CausationId { get; init; }

    The causation identifier for tracking the origin of the message.

  • propertyCorrelationId
    public string? CorrelationId { get; init; }

    The correlation identifier for distributed tracing.

  • propertyCreatedAt
    public DateTimeOffset CreatedAt { get; init; }

    The date and time when the original message was stored in the outbox.

  • propertyDeadLetteredAt
    public DateTimeOffset DeadLetteredAt { get; init; }

    The date and time when the message was moved to the dead-letter queue.

  • propertyHeaders
    public ReadOnlyMemory<byte> Headers { get; init; }

    The serialized JSON representation of custom metadata headers.

  • propertyId
    public Guid Id { get; init; }

    The unique identifier of the dead-letter record.

  • propertyLastError
    public string? LastError { get; init; }

    The full text or stack trace of the last error encountered during dispatch.

  • propertyMessageType
    public string MessageType { get; init; }

    The stable string alias representing the message type.

  • propertyOriginalMessageId
    public Guid OriginalMessageId { get; init; }

    The unique identifier of the original outbox message.

  • propertyPayload
    public ReadOnlyMemory<byte> Payload { get; init; }

    The serialized message content.

  • propertyReason
    public string Reason { get; init; }

    A brief description or code indicating the reason for dead-lettering.

  • propertyRetryCount
    public int RetryCount { get; init; }

    The total number of retry attempts made before the message was dead-lettered.

class

DefaultOutbox

Ensamblado: EricksonLopez.Outbox
public sealed class DefaultOutbox : IOutbox
Implementa: IOutbox

Provides the default implementation of the `IOutbox` interface.

Notas:

Coordinates the serialization, type resolution, and database persistence of outbox messages. It is designed for maximum throughput and zero-allocation on the hot path.

Miembros (5)

  • constructorDefaultOutbox
    public DefaultOutbox(IOutboxRepository repository, IOutboxSerializer serializer, IOutboxMessageTypeResolver typeResolver, Microsoft.Extensions.Options.IOptions<OutboxRuntimeOptions> options, OutboxMetrics metrics, TimeProvider? timeProvider = null)

    Initializes a new instance of the `DefaultOutbox` class.

    repository: IOutboxRepository
    The repository used to persist outbox messages.
    serializer: IOutboxSerializer
    The serializer that converts message payloads to byte arrays.
    typeResolver: IOutboxMessageTypeResolver
    The resolver used to map message types to their string aliases.
    options: Microsoft.Extensions.Options.IOptions<OutboxRuntimeOptions>
    The configuration options for the outbox runtime.
    metrics: OutboxMetrics
    The telemetry metrics tracker.
    timeProvider: TimeProvider?
    The optional time provider for timestamping and deadline calculations.

    Exceptions: ArgumentNullException: Any of the provided arguments is `null`

  • methodPublish<TMessage>
    public OutboxMessageBuilder<TMessage> Publish<TMessage>(TMessage message) where TMessage : notnull

    Begins a fluent message-building chain for enriching a message before persisting it to the outbox.

    message: TMessage
    The initial message payload to begin enriching.

    Retorna: A fluent builder instance to configure transaction, delay, metadata, and headers.

    Type parameters: TMessage: The type of the message being built.

  • methodStoreAsync<TMessage>
    public async ValueTask StoreAsync<TMessage>(ReadOnlyMemory<TMessage> messages, IOutboxTransactionContext transaction, CancellationToken cancellationToken = default) where TMessage : notnull

    Stores a single message atomically within the specified transaction.

    messages: ReadOnlyMemory<TMessage>
    transaction: IOutboxTransactionContext
    The transaction context that scopes this operation.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A `ValueTask` representing the asynchronous store operation.

    Payload and header size limits are enforced at serialization time. If the serialized payload exceeds `OutboxRuntimeOptions.MaxPayloadSizeInBytes`, an `OutboxPayloadTooLargeException` is thrown. If serialized headers exceed `OutboxRuntimeOptions.MaxHeaderSizeInBytes`, an `OutboxHeadersTooLargeException` is thrown. Both exception types are defined in `EricksonLopez.Outbox.dll`. Type parameters: TMessage: The type of the message to store. Exceptions: ArgumentNullException: Thrown when `transaction` is `null`; System.InvalidOperationException: Thrown if the message type alias is not registered and `OutboxRuntimeOptions.ThrowOnUnregisteredType` is `true` (`OutboxTypeNotRegisteredException`, a subtype of `OutboxException`)

  • methodStoreAsync<TMessage>
    public ValueTask StoreAsync<TMessage>(TMessage message, IOutboxTransactionContext transaction, CancellationToken cancellationToken = default) where TMessage : notnull

    Stores a single message atomically within the specified transaction.

    message: TMessage
    The message payload to store in the outbox.
    transaction: IOutboxTransactionContext
    The transaction context that scopes this operation.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A `ValueTask` representing the asynchronous store operation.

    Payload and header size limits are enforced at serialization time. If the serialized payload exceeds `OutboxRuntimeOptions.MaxPayloadSizeInBytes`, an `OutboxPayloadTooLargeException` is thrown. If serialized headers exceed `OutboxRuntimeOptions.MaxHeaderSizeInBytes`, an `OutboxHeadersTooLargeException` is thrown. Both exception types are defined in `EricksonLopez.Outbox.dll`. Type parameters: TMessage: The type of the message to store. Exceptions: ArgumentNullException: Thrown when `transaction` is `null`; System.InvalidOperationException: Thrown if the message type alias is not registered and `OutboxRuntimeOptions.ThrowOnUnregisteredType` is `true` (`OutboxTypeNotRegisteredException`, a subtype of `OutboxException`)

  • methodStoreAsync<TMessage>
    public ValueTask StoreAsync<TMessage>(TMessage message, IOutboxTransactionContext transaction, OutboxMessageMetadata metadata, DateTimeOffset? deliverAt, CancellationToken cancellationToken = default) where TMessage : notnull

    Stores a single message with explicit metadata and scheduling atomically within the specified transaction.

    message: TMessage
    The message payload to store in the outbox.
    transaction: IOutboxTransactionContext
    The transaction context that scopes this operation.
    metadata: OutboxMessageMetadata
    The metadata associated with the message, such as correlation or causation IDs.
    deliverAt: DateTimeOffset?
    An optional future timestamp indicating when the message should become visible for dispatching.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A `ValueTask` representing the asynchronous storage operation.

    Payload and header size limits are enforced at serialization time. If the serialized payload exceeds `OutboxRuntimeOptions.MaxPayloadSizeInBytes`, an `OutboxPayloadTooLargeException` is thrown. If serialized headers exceed `OutboxRuntimeOptions.MaxHeaderSizeInBytes`, an `OutboxHeadersTooLargeException` is thrown. Both exception types are defined in `EricksonLopez.Outbox.dll`. Type parameters: TMessage: The type of the message to store. Exceptions: ArgumentNullException: Thrown when `transaction` is `null`

struct

DispatchContext

Ensamblado: EricksonLopez.Outbox
public readonly struct DispatchContext

Encapsulates contextual information for a message dispatch operation.

Miembros (3)

  • constructorDispatchContext
    public DispatchContext(CancellationToken cancellationToken, int attempt)

    Initializes a new instance of the `DispatchContext` struct.

    cancellationToken: CancellationToken
    The cancellation token for the operation.
    attempt: int
    The current attempt number.
  • propertyAttempt
    public int Attempt { get; }

    Gets the current attempt number for this specific dispatch operation.

  • propertyCancellationToken
    public CancellationToken CancellationToken { get; }

    Gets the cancellation token used to signal that the dispatch operation should be aborted.

record

DispatchResult

Ensamblado: EricksonLopez.Outbox
public readonly record struct DispatchResult(bool Success, bool ShouldRetry, Exception? Error, bool IncrementRetryCount)

Represents the result of a single message dispatch attempt through an `IBrokerPublisher`.

Notas:

Valid state combinations: **Success**: **ShouldRetry**: **Meaning**: - **true**: **false**: **Published successfully.**: - **false**: **true**: **Transient failure — schedule retry with exponential backoff.**: - **false**: **false**: **Fatal failure — dead-letter the message, do not retry.**: IBrokerPublisher contract guidance: Return `FailAndRetry(Exception)` for recoverable errors (network timeout, broker unavailable, rate-limited). Return `FailFatal(Exception)` for unrecoverable errors (serialization failure, schema mismatch, message too large for broker).

Miembros (12)

  • constructorDispatchResult
    public DispatchResult(bool Success, bool ShouldRetry, Exception? Error, bool IncrementRetryCount)

    Initializes a new instance of DispatchResult.

    Success: bool
    Indicates whether the message was successfully dispatched.
    ShouldRetry: bool
    Indicates whether the dispatch operation should be retried after a failure.
    Error: Exception?
    The exception that caused the failure, if any; otherwise, `null`.
    IncrementRetryCount: bool
    Indicates whether the dispatcher should increment the retry counter for the message.

    Valid state combinations: **Success**: **ShouldRetry**: **Meaning**: - **true**: **false**: **Published successfully.**: - **false**: **true**: **Transient failure — schedule retry with exponential backoff.**: - **false**: **false**: **Fatal failure — dead-letter the message, do not retry.**: IBrokerPublisher contract guidance: Return `DispatchResult.FailAndRetry(Exception)` for recoverable errors (network timeout, broker unavailable, rate-limited). Return `DispatchResult.FailFatal(Exception)` for unrecoverable errors (serialization failure, schema mismatch, message too large for broker).

  • methodFailAndRetry
    public static DispatchResult FailAndRetry(Exception ex)

    Creates a transient failure result that will trigger an exponential-backoff retry.

    ex: Exception
    The exception representing the transient failure.

    Retorna: A `DispatchResult` representing a transient failure.

    Use this for recoverable errors such as network timeouts, broker unavailability, or rate limiting.

  • methodFailAndRetry
    public static DispatchResult FailAndRetry(Exception ex, bool incrementRetryCount)

    Creates a transient failure result that will trigger an exponential-backoff retry.

    ex: Exception
    The exception representing the transient failure.
    incrementRetryCount: bool
    Indicates whether to increment the message's retry counter.

    Retorna: A `DispatchResult` representing a transient failure.

  • methodFailFatal
    public static DispatchResult FailFatal(Exception ex)

    Creates a fatal failure result that will dead-letter the message without further retries.

    ex: Exception
    The exception representing the fatal failure.

    Retorna: A `DispatchResult` representing a fatal failure.

    Use this for unrecoverable errors such as serialization failure, schema mismatch, or an oversized payload.

  • methodFailFatal
    public static DispatchResult FailFatal(Guid messageId, int retryCount, string reason)

    Creates a fatal failure result that will dead-letter the message without further retries.

    messageId: Guid
    The identifier of the message that failed.
    retryCount: int
    The current retry count of the message.
    reason: string
    The string message explaining the fatal failure.

    Retorna: A `DispatchResult` representing a fatal failure.

  • methodFailFatal
    public static DispatchResult FailFatal(string reason)

    Creates a fatal failure result with a reason, indicating that the message should not be retried.

    reason: string
    The reason for the fatal failure.

    Retorna: A `DispatchResult` representing a fatal failure.

  • methodOk
    public static DispatchResult Ok()

    Creates a successful dispatch result.

    Retorna: A `DispatchResult` representing a successful dispatch.

  • methodThrowIfInvalid
    public void ThrowIfInvalid()

    Validates the state of the dispatch result and throws an exception if the state is logically invalid.

    Exceptions: InvalidOperationException: Thrown when the result is in an incoherent state, such as `Success=true` and `ShouldRetry=true`

  • propertyError
    public Exception? Error { get; init; }

    The exception that caused the failure, if any; otherwise, `null`.

  • propertyIncrementRetryCount
    public bool IncrementRetryCount { get; init; }

    Indicates whether the dispatcher should increment the retry counter for the message.

  • propertyShouldRetry
    public bool ShouldRetry { get; init; }

    Indicates whether the dispatch operation should be retried after a failure.

  • propertySuccess
    public bool Success { get; init; }

    Indicates whether the message was successfully dispatched.

record

FailedMessage

Ensamblado: EricksonLopez.Outbox
public readonly record struct FailedMessage(Guid Id, Guid OriginalMessageId, string MessageType, ReadOnlyMemory<byte> Payload, string? CorrelationId, string? CausationId, ReadOnlyMemory<byte> Headers, DateTimeOffset CreatedAt, DateTimeOffset FailedAt, string? Error, int RetryCount, DateTimeOffset? NextRetryAt)

Represents a message that failed to dispatch and is pending retry.

Notas:

Once the retry count exceeds the policy maximum, it graduates to a `DeadLetterMessage`.

Miembros (14)

  • constructorFailedMessage
    public FailedMessage(Guid Id, Guid OriginalMessageId, string MessageType, ReadOnlyMemory<byte> Payload, string? CorrelationId, string? CausationId, ReadOnlyMemory<byte> Headers, DateTimeOffset CreatedAt, DateTimeOffset FailedAt, string? Error, int RetryCount, DateTimeOffset? NextRetryAt)

    Initializes a new instance of FailedMessage.

    Id: Guid
    The unique identifier of the failed message record.
    OriginalMessageId: Guid
    The unique identifier of the original outbox message.
    MessageType: string
    The stable string alias representing the message type.
    Payload: ReadOnlyMemory<byte>
    The serialized message content.
    CorrelationId: string?
    The correlation identifier for distributed tracing.
    CausationId: string?
    The causation identifier for tracking the origin of the message.
    Headers: ReadOnlyMemory<byte>
    The serialized JSON representation of custom metadata headers.
    CreatedAt: DateTimeOffset
    The date and time when the original message was stored in the outbox.
    FailedAt: DateTimeOffset
    The date and time when the most recent dispatch attempt failed.
    Error: string?
    The exception message or stack trace associated with the failure.
    RetryCount: int
    The number of times this message has failed dispatch.
    NextRetryAt: DateTimeOffset?
    The optional future timestamp indicating when the next retry attempt should occur.
  • methodFromOutboxMessage
    public static FailedMessage FromOutboxMessage(OutboxMessage original, int retryCount, string? error, TimeSpan? retryAfter = null)

    Creates a `FailedMessage` from an `OutboxMessage` after a dispatch failure.

    original: OutboxMessage
    The original outbox message that failed.
    retryCount: int
    The current retry attempt number.
    error: string?
    The exception message or stack trace associated with the failure.
    retryAfter: TimeSpan?
    The optional time interval to wait before the next retry attempt.

    Retorna: A new `FailedMessage` instance representing the pending retry state.

  • propertyCausationId
    public string? CausationId { get; init; }

    The causation identifier for tracking the origin of the message.

  • propertyCorrelationId
    public string? CorrelationId { get; init; }

    The correlation identifier for distributed tracing.

  • propertyCreatedAt
    public DateTimeOffset CreatedAt { get; init; }

    The date and time when the original message was stored in the outbox.

  • propertyError
    public string? Error { get; init; }

    The exception message or stack trace associated with the failure.

  • propertyFailedAt
    public DateTimeOffset FailedAt { get; init; }

    The date and time when the most recent dispatch attempt failed.

  • propertyHeaders
    public ReadOnlyMemory<byte> Headers { get; init; }

    The serialized JSON representation of custom metadata headers.

  • propertyId
    public Guid Id { get; init; }

    The unique identifier of the failed message record.

  • propertyMessageType
    public string MessageType { get; init; }

    The stable string alias representing the message type.

  • propertyNextRetryAt
    public DateTimeOffset? NextRetryAt { get; init; }

    The optional future timestamp indicating when the next retry attempt should occur.

  • propertyOriginalMessageId
    public Guid OriginalMessageId { get; init; }

    The unique identifier of the original outbox message.

  • propertyPayload
    public ReadOnlyMemory<byte> Payload { get; init; }

    The serialized message content.

  • propertyRetryCount
    public int RetryCount { get; init; }

    The number of times this message has failed dispatch.

interface

IBrokerPublisher

Ensamblado: EricksonLopez.Outbox
public interface IBrokerPublisher

Defines a broker-agnostic contract for publishing messages to a message broker.

Notas:

All broker adapters implement this contract. Design rationale: - The generic overloads are intended for strongly-typed publishing at the application boundary. - The raw overload is used by the dispatcher, operating on already-serialized `OutboxMessage` without needing to reconstruct generics at dispatch time, ensuring NativeAOT compatibility. Dispatcher usage: The core dispatcher exclusively uses `PublishRawAsync` (per-message path). `ITypedBrokerPublisher.PublishBatchAsync<T>` is provided for use in application code (e.g., event fanning-out within a single transaction).

Miembros (2)

  • methodPublishRawAsync
    ValueTask<DispatchResult> PublishRawAsync(OutboxMessage message, OutboxMessageMetadata metadata, DispatchContext context)

    Publishes a raw serialized outbox message as-is.

    message: OutboxMessage
    The raw outbox message to publish.
    metadata: OutboxMessageMetadata
    The metadata associated with the message.
    context: DispatchContext
    The context governing the dispatch operation, including cancellation tokens.

    Retorna: A task that represents the asynchronous dispatch operation, containing the `DispatchResult`.

    Used by the Dispatcher which works with pre-serialized payloads, avoiding runtime generics and reflection for NativeAOT compatibility. DispatchResult contract for implementers: **Scenario**: **Return value**: - **Message published successfully**: **`DispatchResult.Ok()`**: - **Transient / recoverable failure (network timeout, broker unreachable, rate-limited)**: **`DispatchResult.FailAndRetry(exception)`**: - **Fatal / unrecoverable failure (schema mismatch, serialization error, message too large for broker, authorization denied)**: **`DispatchResult.FailFatal(exception)`**: Do NOT throw exceptions here. Thrown exceptions are treated as fatal failures by the dispatcher (equivalent to `DispatchResult.FailFatal`). Always catch broker exceptions and map them to the appropriate `DispatchResult`. Do NOT return `default(DispatchResult)`. The default value of the struct (`Success=false, ShouldRetry=false, Error=null`) is an invalid state that will cause the dispatcher to dead-letter the message with a misleading "no error" state. Always use one of the factory methods: `DispatchResult.Ok()`, `DispatchResult.FailAndRetry(ex)`, or `DispatchResult.FailFatal(ex)`. The dispatcher wraps calls to the publisher with a retry interceptor, which automatically retries `FailAndRetry` results with exponential backoff. Returning `FailFatal` bypasses retry and dead-letters the message immediately. OpenTelemetry — `messaging.system` tag requirement: The outbox core sets `messaging.system = "outbox"` as a default on the dispatch Activity. Broker implementers MUST override this tag with the actual broker name: `System.Diagnostics.Activity.Current?.SetTag("messaging.system", "rabbitmq"); // or "kafka", "azure_service_bus", etc.` This is required by the OpenTelemetry Messaging Semantic Conventions (v1.26+): https://opentelemetry.io/docs/specs/semconv/messaging/messaging-spans/#messaging-attributes

  • propertyBrokerSystemName
    string BrokerSystemName { get; }

    Gets the OpenTelemetry `messaging.system` attribute value for this broker implementation.

    The outbox dispatcher reads this value to set the `messaging.system` tag on the dispatch `Diagnostics.Activity`, conforming to the OpenTelemetry Messaging Semantic Conventions (v1.26+). See: https://opentelemetry.io/docs/specs/semconv/messaging/messaging-spans/ Override this property in your broker publisher to return the canonical OTel system name: **Broker**: **Return value**: - **RabbitMQ**: **`"rabbitmq"`**: - **Apache Kafka**: **`"kafka"`**: - **Azure Service Bus**: **`"azure_service_bus"`**: - **Amazon SQS**: **`"aws_sqs"`**: - **Google Pub/Sub**: **`"gcp_pubsub"`**: - **NATS**: **`"nats"`**: - **Redis Streams**: **`"redis"`**: The default implementation returns `"outbox"` as a fallback sentinel value. The dispatcher will use this value automatically — broker publishers no longer need to call `Activity.Current?.SetTag("messaging.system", ...)` manually.

interface

IBrokerSelector

Ensamblado: EricksonLopez.Outbox
public interface IBrokerSelector

Selects the appropriate `IBrokerPublisher` for a given outbox message.

Miembros (1)

  • methodGetPublisher
    IBrokerPublisher GetPublisher(OutboxMessage message)

    Gets the publisher for the specified message.

    message: OutboxMessage
    The outbox message being dispatched.

    Retorna: The `IBrokerPublisher` responsible for publishing the message.

    Exceptions: InvalidOperationException: Thrown when no suitable publisher is found

interface

IOutbox

Ensamblado: EricksonLopez.Outbox.Abstractions
public interface IOutbox

Defines the primary entry point for storing messages in the outbox using a transaction context.

Miembros (3)

  • methodStoreAsync<TMessage>
    ValueTask StoreAsync<TMessage>(ReadOnlyMemory<TMessage> messages, IOutboxTransactionContext transaction, CancellationToken cancellationToken = default) where TMessage : notnull

    Stores a batch of messages atomically within the specified transaction.

    messages: ReadOnlyMemory<TMessage>
    A memory region containing the batch of messages to store.
    transaction: IOutboxTransactionContext
    The transaction context that scopes this operation.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous batch storage operation.

    Type parameters: TMessage: The type of the messages to store. Exceptions: ArgumentNullException: Thrown when `transaction` is `null`

  • methodStoreAsync<TMessage>
    ValueTask StoreAsync<TMessage>(TMessage message, IOutboxTransactionContext transaction, CancellationToken cancellationToken = default) where TMessage : notnull

    Stores a single message atomically within the specified transaction.

    message: TMessage
    The message payload to store in the outbox.
    transaction: IOutboxTransactionContext
    The transaction context that scopes this operation.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A `ValueTask` representing the asynchronous store operation.

    Payload and header size limits are enforced at serialization time. If the serialized payload exceeds `OutboxRuntimeOptions.MaxPayloadSizeInBytes`, an `OutboxPayloadTooLargeException` is thrown. If serialized headers exceed `OutboxRuntimeOptions.MaxHeaderSizeInBytes`, an `OutboxHeadersTooLargeException` is thrown. Both exception types are defined in `EricksonLopez.Outbox.dll`. Type parameters: TMessage: The type of the message to store. Exceptions: ArgumentNullException: Thrown when `transaction` is `null`; System.InvalidOperationException: Thrown if the message type alias is not registered and `OutboxRuntimeOptions.ThrowOnUnregisteredType` is `true` (`OutboxTypeNotRegisteredException`, a subtype of `OutboxException`)

  • methodStoreAsync<TMessage>
    ValueTask StoreAsync<TMessage>(TMessage message, IOutboxTransactionContext transaction, OutboxMessageMetadata metadata, DateTimeOffset? deliverAt, CancellationToken cancellationToken = default) where TMessage : notnull

    Stores a single message with explicit metadata and scheduling atomically within the specified transaction.

    message: TMessage
    The message payload to store in the outbox.
    transaction: IOutboxTransactionContext
    The transaction context that scopes this operation.
    metadata: OutboxMessageMetadata
    The metadata associated with the message, such as correlation or causation IDs.
    deliverAt: DateTimeOffset?
    An optional future timestamp indicating when the message should become visible for dispatching.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A `ValueTask` representing the asynchronous storage operation.

    Payload and header size limits are enforced at serialization time. If the serialized payload exceeds `OutboxRuntimeOptions.MaxPayloadSizeInBytes`, an `OutboxPayloadTooLargeException` is thrown. If serialized headers exceed `OutboxRuntimeOptions.MaxHeaderSizeInBytes`, an `OutboxHeadersTooLargeException` is thrown. Both exception types are defined in `EricksonLopez.Outbox.dll`. Type parameters: TMessage: The type of the message to store. Exceptions: ArgumentNullException: Thrown when `transaction` is `null`

interface

IOutboxCollector

Ensamblado: EricksonLopez.Outbox.Abstractions
public interface IOutboxCollector

Buffers integration messages in-memory during command or pre-commit domain event execution so they can be flushed atomically inside the active database transaction prior to `CommitAsync`.

Miembros (3)

  • methodClear
    void Clear()

    Discards all buffered messages (invoked upon transaction rollback or exception).

  • methodEnqueue<TMessage>
    void Enqueue<TMessage>(TMessage message, OutboxMessageMetadata metadata = default, DateTimeOffset? deliverAt = null) where TMessage : notnull

    Stages a strongly-typed integration message for pre-commit transactional persistence.

    message: TMessage
    The non-null message payload.
    metadata: OutboxMessageMetadata
    Optional correlation, causation, tenant, company, and custom headers.
    deliverAt: DateTimeOffset?
    Optional scheduled UTC delivery timestamp.

    Type parameters: TMessage: The concrete integration message type (serialized without runtime reflection).

  • propertyPendingCount
    int PendingCount { get; }

    Gets the number of buffered messages currently awaiting pre-commit persistence.

interface

IOutboxDispatchContextAccessor

Ensamblado: EricksonLopez.Outbox.Abstractions
public interface IOutboxDispatchContextAccessor

Exposes the rehydrated `OutboxDispatchTenantContext` (`TenantId`, `CompanyId`, `ExecutionPlane`) for the outbox message currently executing on the background dispatch pipeline.

Miembros (2)

  • methodBeginScope
    IDisposable BeginScope(OutboxDispatchTenantContext context)

    Establishes an ambient `OutboxDispatchTenantContext` scope for the current asynchronous flow.

    context: OutboxDispatchTenantContext
    The rehydrated dispatch tenant context.

    Retorna: An `IDisposable` token that restores the previous context on disposal.

  • propertyCurrent
    OutboxDispatchTenantContext? Current { get; }

    Gets the ambient dispatch tenant context for the currently executing outbox message, or `null` outside dispatch.

interface

ITypedBrokerPublisher

Ensamblado: EricksonLopez.Outbox
public interface ITypedBrokerPublisher : IBrokerPublisher
Implementa: IBrokerPublisher

Defines a contract extending `IBrokerPublisher` to support strongly-typed message publishing.

Miembros (2)

  • methodPublishAsync<T>
    ValueTask<DispatchResult> PublishAsync<T>(MessageEnvelope<T> message, DispatchContext context) where T : notnull

    Publishes a strongly-typed message envelope to the underlying broker.

    message: MessageEnvelope<T>
    The message envelope containing payload and metadata.
    context: DispatchContext
    The context governing the dispatch operation.

    Retorna: A task representing the asynchronous operation, containing the `DispatchResult`.

    Type parameters: T: The type of the message payload.

  • methodPublishBatchAsync<T>
    ValueTask<IReadOnlyList<DispatchResult>> PublishBatchAsync<T>(IReadOnlyList<MessageEnvelope<T>> messages, DispatchContext context) where T : notnull

    Publishes a batch of strongly-typed message envelopes to the underlying broker.

    messages: IReadOnlyList<MessageEnvelope<T>>
    The read-only list of message envelopes to publish.
    context: DispatchContext
    The context governing the dispatch operation.

    Retorna: A task representing the asynchronous operation, containing the list of dispatch results.

    Type parameters: T: The type of the message payload.

record

IdempotencyRecord

Ensamblado: EricksonLopez.Outbox.Abstractions
public readonly record struct IdempotencyRecord(string MessageId, string ConsumerId, DateTimeOffset ProcessedAt)

Represents a record used to ensure idempotent processing of messages within the Inbox.

Miembros (4)

  • constructorIdempotencyRecord
    public IdempotencyRecord(string MessageId, string ConsumerId, DateTimeOffset ProcessedAt)

    Initializes a new instance of IdempotencyRecord.

    MessageId: string
    The unique identifier of the processed message.
    ConsumerId: string
    The unique identifier of the consumer that processed the message.
    ProcessedAt: DateTimeOffset
    The exact date and time the message was successfully processed.
  • propertyConsumerId
    public string ConsumerId { get; init; }

    The unique identifier of the consumer that processed the message.

  • propertyMessageId
    public string MessageId { get; init; }

    The unique identifier of the processed message.

  • propertyProcessedAt
    public DateTimeOffset ProcessedAt { get; init; }

    The exact date and time the message was successfully processed.

record

InboxMessage

Ensamblado: EricksonLopez.Outbox
public readonly record struct InboxMessage(Guid Id, string MessageType, ReadOnlyMemory<byte> Payload, string? CorrelationId, string? CausationId, ReadOnlyMemory<byte> Headers, DateTimeOffset ReceivedAt, DateTimeOffset? ProcessedAt, int Status, string? Error)

Represents a message received from a message broker and stored in the Inbox for idempotent processing.

Miembros (11)

  • constructorInboxMessage
    public InboxMessage(Guid Id, string MessageType, ReadOnlyMemory<byte> Payload, string? CorrelationId, string? CausationId, ReadOnlyMemory<byte> Headers, DateTimeOffset ReceivedAt, DateTimeOffset? ProcessedAt, int Status, string? Error)

    Initializes a new instance of InboxMessage.

    Id: Guid
    The unique identifier of the inbox message.
    MessageType: string
    The stable string alias representing the message type.
    Payload: ReadOnlyMemory<byte>
    The serialized message content.
    CorrelationId: string?
    The correlation identifier for distributed tracing.
    CausationId: string?
    The causation identifier for tracking the origin of the message.
    Headers: ReadOnlyMemory<byte>
    The serialized JSON representation of custom metadata headers.
    ReceivedAt: DateTimeOffset
    The date and time when the message was received and stored in the inbox.
    ProcessedAt: DateTimeOffset?
    The date and time when the message was successfully processed by the consumer, if applicable.
    Status: int
    The current processing status of the inbox message.
    Error: string?
    The last error message encountered during a failed processing attempt, if any.
  • propertyCausationId
    public string? CausationId { get; init; }

    The causation identifier for tracking the origin of the message.

  • propertyCorrelationId
    public string? CorrelationId { get; init; }

    The correlation identifier for distributed tracing.

  • propertyError
    public string? Error { get; init; }

    The last error message encountered during a failed processing attempt, if any.

  • propertyHeaders
    public ReadOnlyMemory<byte> Headers { get; init; }

    The serialized JSON representation of custom metadata headers.

  • propertyId
    public Guid Id { get; init; }

    The unique identifier of the inbox message.

  • propertyMessageType
    public string MessageType { get; init; }

    The stable string alias representing the message type.

  • propertyPayload
    public ReadOnlyMemory<byte> Payload { get; init; }

    The serialized message content.

  • propertyProcessedAt
    public DateTimeOffset? ProcessedAt { get; init; }

    The date and time when the message was successfully processed by the consumer, if applicable.

  • propertyReceivedAt
    public DateTimeOffset ReceivedAt { get; init; }

    The date and time when the message was received and stored in the inbox.

  • propertyStatus
    public int Status { get; init; }

    The current processing status of the inbox message.

record

Lease

Ensamblado: EricksonLopez.Outbox
public readonly record struct Lease(string ResourceId, string OwnerId, DateTimeOffset ExpiresAt)

Represents a time-bound, exclusive lease on a specific resource.

Miembros (5)

  • constructorLease
    public Lease(string ResourceId, string OwnerId, DateTimeOffset ExpiresAt)

    Initializes a new instance of Lease.

    ResourceId: string
    The unique identifier of the leased resource.
    OwnerId: string
    The unique identifier of the process or instance that currently holds the lease.
    ExpiresAt: DateTimeOffset
    The absolute UTC timestamp when the lease expires and the resource becomes available again.
  • methodIsExpired
    public bool IsExpired(DateTimeOffset now)

    Determines whether the lease has expired relative to the specified timestamp.

    now: DateTimeOffset
    The current UTC timestamp to evaluate against the lease expiration.

    Retorna: `true` if the lease is expired; otherwise, `false`.

  • propertyExpiresAt
    public DateTimeOffset ExpiresAt { get; init; }

    The absolute UTC timestamp when the lease expires and the resource becomes available again.

  • propertyOwnerId
    public string OwnerId { get; init; }

    The unique identifier of the process or instance that currently holds the lease.

  • propertyResourceId
    public string ResourceId { get; init; }

    The unique identifier of the leased resource.

record

Lock

Ensamblado: EricksonLopez.Outbox
public readonly record struct Lock(string ResourceId, string OwnerId)

Represents an exclusive lock acquired on a specific resource.

Miembros (3)

  • constructorLock
    public Lock(string ResourceId, string OwnerId)

    Initializes a new instance of Lock.

    ResourceId: string
    The unique identifier of the locked resource.
    OwnerId: string
    The unique identifier of the process or instance that acquired the lock.
  • propertyOwnerId
    public string OwnerId { get; init; }

    The unique identifier of the process or instance that acquired the lock.

  • propertyResourceId
    public string ResourceId { get; init; }

    The unique identifier of the locked resource.

record

MessageEnvelope<T>

Ensamblado: EricksonLopez.Outbox
public readonly record struct MessageEnvelope<T>(T Payload, OutboxMessageMetadata Metadata) where T : notnull

Wraps a strongly-typed message payload along with its associated metadata for publishing.

Notas:

Type parameters: T: The type of the message payload being enveloped.

Miembros (3)

  • constructorMessageEnvelope
    public MessageEnvelope(T Payload, OutboxMessageMetadata Metadata)

    Initializes a new instance of MessageEnvelope<T>.

    Payload: T
    The strongly-typed message payload.
    Metadata: OutboxMessageMetadata
    The metadata associated with the message, such as headers and tracing identifiers.

    Type parameters: T: The type of the message payload being enveloped.

  • propertyMetadata
    public OutboxMessageMetadata Metadata { get; init; }

    The metadata associated with the message, such as headers and tracing identifiers.

  • propertyPayload
    public T Payload { get; init; }

    The strongly-typed message payload.

record

MetadataEntry

Ensamblado: EricksonLopez.Outbox.Abstractions
public readonly record struct MetadataEntry(string Key, string Value)

Represents a single key-value pair of metadata associated with a message.

Miembros (3)

  • constructorMetadataEntry
    public MetadataEntry(string Key, string Value)

    Initializes a new instance of MetadataEntry.

    Key: string
    The key identifying the metadata entry.
    Value: string
    The value of the metadata entry.
  • propertyKey
    public string Key { get; init; }

    The key identifying the metadata entry.

  • propertyValue
    public string Value { get; init; }

    The value of the metadata entry.

class

OutboxCleanupOptions

Ensamblado: EricksonLopez.Outbox
public sealed class OutboxCleanupOptions

Configuration options for `Hosting.OutboxCleanupService`.

Miembros (4)

  • propertyBatchSize
    public int BatchSize { get; set; }

    Gets or sets the maximum number of rows deleted in a single purge batch to avoid table lock escalation. Default is 1000.

  • propertyCleanupInterval
    public TimeSpan CleanupInterval { get; set; }

    Gets or sets the interval between successive cleanup execution passes. Default is 1 hour.

  • propertyEnabled
    public bool Enabled { get; set; }

    Gets or sets a value indicating whether the background cleanup service is enabled. Default is `false` (opt-in).

  • propertyRetentionPeriod
    public TimeSpan RetentionPeriod { get; set; }

    Gets or sets the retention duration for dispatched outbox messages. Messages dispatched prior to `UtcNow - RetentionPeriod` will be purged. Default is 7 days.

class

OutboxConfigurationException

Ensamblado: EricksonLopez.Outbox
public sealed class OutboxConfigurationException : OutboxException
Hereda de: OutboxException

Thrown when the startup validator detects missing or misconfigured required services.

Miembros (1)

  • constructorOutboxConfigurationException
    public OutboxConfigurationException(string message)

    Initializes a new instance of the `OutboxConfigurationException` class with a specified error message.

    message: string
    The message that describes the configuration error.
class

OutboxConstants

Ensamblado: EricksonLopez.Outbox
public static class OutboxConstants

Provides well-known string constants for the EricksonLopez.Outbox library.

Notas:

Using named constants for consumer IDs prevents silent collisions between the dispatcher's internal idempotency records and user-defined consumers. Always pass an explicit, unique `consumerId` per consumer in your application; do not reuse `DispatcherConsumerId` in user-facing consumers.

Miembros (1)

  • fieldDispatcherConsumerId
    public const string DispatcherConsumerId

    Defines the consumer identifier used internally by the outbox dispatcher to track its own idempotency records via `IInboxIdempotencyChecker.ShouldSkipAsync`.

    This constant is the default value for the `consumerId` parameter of `IInboxIdempotencyChecker.ShouldSkipAsync`. It should only be used by the dispatcher infrastructure. DO NOT use this constant in your own consumers. Doing so would cause your consumer's idempotency records to collide with the dispatcher's records, resulting in incorrect duplicate-detection behavior (messages already processed by the dispatcher would appear as duplicates to your consumer, or vice versa). Use a stable, unique string per consumer instead, for example: `"order-service.payment-handler"`.

class

OutboxDispatchException

Ensamblado: EricksonLopez.Outbox
public sealed class OutboxDispatchException : OutboxException
Hereda de: OutboxException

Thrown when a dispatch operation fails fatally after exhausting all retry policies.

Miembros (3)

  • constructorOutboxDispatchException
    public OutboxDispatchException(Guid messageId, int attemptCount, string message, Exception? innerException = null)

    Initializes a new instance of the `OutboxDispatchException` class.

    messageId: Guid
    The unique identifier of the failed message.
    attemptCount: int
    The number of dispatch attempts made.
    message: string
    The message that describes the error.
    innerException: Exception?
    The optional exception that is the cause of the current exception.
  • propertyAttemptCount
    public int AttemptCount { get; }

    Gets the number of attempts made to dispatch the message before failing.

  • propertyMessageId
    public Guid MessageId { get; }

    Gets the unique identifier of the message that failed to dispatch.

record

OutboxDispatchTenantContext

Ensamblado: EricksonLopez.Outbox.Abstractions
public readonly record struct OutboxDispatchTenantContext(string? TenantId, string? CompanyId, string ExecutionPlane)

Represents the rehydrated multi-plane tenant and company identity extracted from an outbox message during background dispatch.

Miembros (5)

  • constructorOutboxDispatchTenantContext
    public OutboxDispatchTenantContext(string? TenantId, string? CompanyId, string ExecutionPlane)

    Initializes a new instance of OutboxDispatchTenantContext.

    TenantId: string?
    The rehydrated tenant identifier, or `null` for control-plane messages.
    CompanyId: string?
    The rehydrated holding company / organization unit identifier, or `null` when unassigned.
    ExecutionPlane: string
    The resolved execution plane wire code (`TENANT` or `CONTROL`).
  • propertyCompanyId
    public string? CompanyId { get; init; }

    The rehydrated holding company / organization unit identifier, or `null` when unassigned.

  • propertyExecutionPlane
    public string ExecutionPlane { get; init; }

    The resolved execution plane wire code (`TENANT` or `CONTROL`).

  • propertyHasTenantOrCompanyScope
    public bool HasTenantOrCompanyScope { get; }

    Gets a value indicating whether either `TenantId` or `CompanyId` carries a non-empty tenant/company scope.

  • propertyTenantId
    public string? TenantId { get; init; }

    The rehydrated tenant identifier, or `null` for control-plane messages.

class

OutboxDispatcherOptions

Ensamblado: EricksonLopez.Outbox
public sealed class OutboxDispatcherOptions

Represents the configuration options for the Outbox Dispatcher background service.

Miembros (13)

  • propertyBatchSize
    public int BatchSize { get; set; }

    Gets or sets the maximum number of messages retrieved from the database per polling cycle.

  • propertyChannelCapacity
    public int ChannelCapacity { get; set; }

    Gets or sets the maximum capacity of the in-memory channel connecting the poller to consumers.

  • propertyDbRetryBaseDelayMs
    public int DbRetryBaseDelayMs { get; set; }

    Gets or sets the base delay in milliseconds between DB operation retry attempts.

  • propertyDbRetryMaxAttempts
    public int DbRetryMaxAttempts { get; set; }

    Gets or sets the maximum number of retry attempts for a transient DB operation failure before the exception propagates.

  • propertyHasOnlySingletonMiddlewares
    public bool HasOnlySingletonMiddlewares { get; set; }

    Gets or sets a value indicating whether all registered pipeline middlewares are registered as singletons. When `true`, the dispatcher caches the built middleware pipeline to avoid per-batch allocations. Defaults to `false`.

  • propertyMaxBatchesPerSecond
    public int MaxBatchesPerSecond { get; set; }

    Gets or sets the maximum number of batches to process per second when adaptive polling is draining a large backlog. A value of 0 means no limit (unbounded).

  • propertyMaxDegreeOfParallelism
    public int MaxDegreeOfParallelism { get; set; }

    Gets or sets the maximum number of concurrent consumer tasks draining the dispatcher channel.

    Configures the number of parallel consumer worker tasks spawned by the dispatcher. Ordering Guarantee: Strict global FIFO publishing order across all messages is only guaranteed when `MaxDegreeOfParallelism` is set to 1 and in the absence of transient retries. When parallelism is greater than 1, concurrent dispatch workers may interleave message deliveries to the underlying broker. For aggregate-level causal ordering, ensure consumer-side partition key routing. Default: `min(ProcessorCount, 8)`.

  • propertyMaxRetryCount
    public int MaxRetryCount { get; set; }

    Gets or sets the maximum number of retry attempts for a failed message dispatch before marking it as permanently failed.

  • propertyPendingCountRefreshInterval
    public TimeSpan PendingCountRefreshInterval { get; set; }

    Gets or sets the interval at which the approximate pending message count is refreshed and emitted as the `messaging.outbox.pending.messages` OpenTelemetry gauge.

  • propertyPollingInterval
    public TimeSpan PollingInterval { get; set; }

    Gets or sets the fixed time interval to wait between polling cycles when the outbox is empty.

  • propertyReclaimInterval
    public TimeSpan ReclaimInterval { get; set; }

    Gets or sets the interval between background checks for stale messages to reclaim.

  • propertyReclaimTimeout
    public TimeSpan ReclaimTimeout { get; set; }

    Gets or sets the timeout duration after which a stuck message is considered stale and available for reclamation.

  • propertyUseAdaptivePolling
    public bool UseAdaptivePolling { get; set; }

    Gets or sets a value indicating whether the dispatcher should dynamically adjust the polling interval based on load.

class

OutboxException

Ensamblado: EricksonLopez.Outbox
public class OutboxException : Exception
Hereda de: Exception

Represents the base class for all exceptions thrown by the EricksonLopez.Outbox library.

Miembros (3)

  • constructorOutboxException
    public OutboxException()

    Initializes a new instance of the `OutboxException` class.

  • constructorOutboxException
    public OutboxException(string message)

    Initializes a new instance of the `OutboxException` class with a specified error message.

    message: string
    The message that describes the error.
  • constructorOutboxException
    public OutboxException(string message, Exception innerException)

    Initializes a new instance of the `OutboxException` class with a specified error message and a reference to the inner exception that is the cause of this exception.

    message: string
    The error message that explains the reason for the exception.
    innerException: Exception
    The exception that is the cause of the current exception.
class

OutboxExtensions

Ensamblado: EricksonLopez.Outbox.Abstractions
public static class OutboxExtensions

Provides convenience extension methods for `IOutbox` to support additional overloads.

Miembros (1)

  • methodStoreAsync<TMessage>
    public static ValueTask StoreAsync<TMessage>(this IOutbox outbox, IEnumerable<TMessage> messages, IOutboxTransactionContext transaction, CancellationToken cancellationToken = default) where TMessage : notnull

    Stores a sequence of messages atomically within the specified transaction.

    outbox: this IOutbox
    The outbox instance.
    messages: IEnumerable<TMessage>
    The sequence of messages to store in the outbox.
    transaction: IOutboxTransactionContext
    The transaction context that scopes this operation.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous batch storage operation.

    Type parameters: TMessage: The type of the messages to store. Exceptions: ArgumentNullException: `outbox` or `messages` is `null`

class

OutboxHeadersTooLargeException

Ensamblado: EricksonLopez.Outbox
public sealed class OutboxHeadersTooLargeException : OutboxException
Hereda de: OutboxException

Thrown when message headers exceed the configured maximum headers size limit.

Miembros (3)

  • constructorOutboxHeadersTooLargeException
    public OutboxHeadersTooLargeException(int actualSize, int maxAllowedSize)

    Initializes a new instance of the `OutboxHeadersTooLargeException` class.

    actualSize: int
    The actual size of the headers in bytes.
    maxAllowedSize: int
    The maximum allowed size for the headers in bytes.
  • propertyActualSize
    public int ActualSize { get; }

    Gets the actual serialized headers size in bytes.

  • propertyMaxAllowedSize
    public int MaxAllowedSize { get; }

    Gets the configured maximum allowed headers size in bytes.

class

OutboxHealthCheckExtensions

Ensamblado: EricksonLopez.Outbox
public static class OutboxHealthCheckExtensions

Provides extension methods for registering outbox health checks.

Miembros (2)

  • methodAddOutbox
    public static IHealthChecksBuilder AddOutbox(this IHealthChecksBuilder builder, string name = "", int? warningThreshold = null, params string[] tags)

    Adds the Outbox health check to the `IHealthChecksBuilder`.

    builder: this IHealthChecksBuilder
    The health checks builder.
    name: string
    The name of the health check registration. Default is `"outbox"`.
    warningThreshold: int?
    The optional warning threshold for pending messages before degrading health status.
    tags: params string[]
    Optional tags used to filter health checks.

    Retorna: The modified `IHealthChecksBuilder` for method chaining.

  • methodAddOutboxCleanupService
    public static IServiceCollection AddOutboxCleanupService(this IServiceCollection services, Action<OutboxCleanupOptions>? configure = null)

    Registers the `OutboxCleanupService` background worker to purge old dispatched outbox messages.

    services: this IServiceCollection
    The service collection to register the service into.
    configure: Action<OutboxCleanupOptions>?
    An optional action to configure `OutboxCleanupOptions`.

    Retorna: The modified `IServiceCollection` for method chaining.

class

OutboxHealthCheckOptions

Ensamblado: EricksonLopez.Outbox
public sealed class OutboxHealthCheckOptions

Represents the configuration options for the Outbox Health Check service.

Miembros (1)

  • propertyWarningThreshold
    public int WarningThreshold { get; set; }

    Gets or sets the threshold of pending messages above which the health check reports a degraded status.

class

OutboxInboxOptions

Ensamblado: EricksonLopez.Outbox
public sealed class OutboxInboxOptions

Represents the configuration options for the Inbox idempotency system.

Miembros (3)

  • propertyCleanupInterval
    public TimeSpan CleanupInterval { get; set; }

    Gets or sets the interval between background cleanup operations for expired idempotency records.

  • propertyDuplicateDetectionWindow
    public TimeSpan DuplicateDetectionWindow { get; set; }

    Gets or sets the time window within which duplicate messages are detected.

  • propertyRetentionPeriod
    public TimeSpan RetentionPeriod { get; set; }

    Gets or sets the duration for which processed idempotency records are retained before being purged.

record

OutboxMessage

Ensamblado: EricksonLopez.Outbox
public sealed record OutboxMessage(Guid Id, string MessageType, ReadOnlyMemory<byte> Payload, string? CorrelationId, string? CausationId, ReadOnlyMemory<byte> Headers, DateTimeOffset CreatedAt, DateTimeOffset? ProcessedAt, DateTimeOffset? DeliverAt, OutboxMessageStatus Status, int RetryCount, string? Error)

Represents the core entity for a single message stored in the outbox database table.

Notas:

All fields map 1:1 to database columns to enable zero-copy hydration from the DB. Performance note: `sealed record` (reference type) is used instead of a struct because this type contains multiple fields. As a struct, every parameter pass, foreach iteration, and method return would copy the entire value. As a class, only the reference is copied. Messages are short-lived (Gen0) objects created during DB hydration and collected after dispatch, so GC pressure is minimal compared to the copy elimination savings.

Miembros (18)

  • constructorOutboxMessage
    public OutboxMessage(Guid Id, string MessageType, ReadOnlyMemory<byte> Payload, string? CorrelationId, string? CausationId, ReadOnlyMemory<byte> Headers, DateTimeOffset CreatedAt, DateTimeOffset? ProcessedAt, DateTimeOffset? DeliverAt, OutboxMessageStatus Status, int RetryCount, string? Error)

    Initializes a new instance of OutboxMessage.

    Id: Guid
    The unique identifier of the outbox message.
    MessageType: string
    The stable string alias representing the message type.
    Payload: ReadOnlyMemory<byte>
    The serialized message content.
    CorrelationId: string?
    The correlation identifier for distributed tracing.
    CausationId: string?
    The causation identifier for tracking the origin of the message.
    Headers: ReadOnlyMemory<byte>
    The serialized JSON representation of custom metadata headers.
    CreatedAt: DateTimeOffset
    The date and time when the message was originally stored in the outbox.
    ProcessedAt: DateTimeOffset?
    The date and time when the message was successfully dispatched to the broker, if applicable.
    DeliverAt: DateTimeOffset?
    The optional future timestamp before which the message must not be dispatched.
    Status: OutboxMessageStatus
    The current dispatch status of the message.
    RetryCount: int
    The number of times this message has failed and been re-fetched from the database. Note: This is NOT the number of internal retry attempts made by the publisher's RetryPolicy.
    Error: string?
    The last error message encountered during a failed dispatch attempt, if any.
  • methodEquals
    public bool Equals(OutboxMessage? other)

    Inherits documentation from base type or interface.

    other: OutboxMessage?
  • methodGetHashCode
    public override int GetHashCode()

    Inherits documentation from base type or interface.

  • propertyCausationId
    public string? CausationId { get; init; }

    The causation identifier for tracking the origin of the message.

  • propertyCompanyId
    public string? CompanyId { get; init; }

    Optional holding company / organization unit identifier when distinct from `TenantId`.

  • propertyCorrelationId
    public string? CorrelationId { get; init; }

    The correlation identifier for distributed tracing.

  • propertyCreatedAt
    public DateTimeOffset CreatedAt { get; init; }

    The date and time when the message was originally stored in the outbox.

  • propertyDeliverAt
    public DateTimeOffset? DeliverAt { get; init; }

    The optional future timestamp before which the message must not be dispatched.

  • propertyError
    public string? Error { get; init; }

    The last error message encountered during a failed dispatch attempt, if any.

  • propertyExtensions
    public IReadOnlyDictionary<string, string>? Extensions { get; init; }

    Optional metadata extensions for future compatibility and custom routing.

    ROADMAP-v2 — Typed extension values: The current type `IReadOnlyDictionary<string, string>` restricts values to strings. This is sufficient for string-based headers (correlation IDs, trace tags, routing keys), but precludes typed values such as Kafka partition offsets (`long`), sequence numbers, or CDC/WAL metadata. In v2.0, consider changing to `IReadOnlyDictionary<string, object?>` or a custom `ExtensionMetadata` type. This is a binary breaking change and is deferred to avoid disrupting v1.0 consumers.

  • propertyHeaders
    public ReadOnlyMemory<byte> Headers { get; init; }

    The serialized JSON representation of custom metadata headers.

  • propertyId
    public Guid Id { get; init; }

    The unique identifier of the outbox message.

  • propertyMessageType
    public string MessageType { get; init; }

    The stable string alias representing the message type.

  • propertyPayload
    public ReadOnlyMemory<byte> Payload { get; init; }

    The serialized message content.

  • propertyProcessedAt
    public DateTimeOffset? ProcessedAt { get; init; }

    The date and time when the message was successfully dispatched to the broker, if applicable.

  • propertyRetryCount
    public int RetryCount { get; init; }

    The number of times this message has failed and been re-fetched from the database. Note: This is NOT the number of internal retry attempts made by the publisher's RetryPolicy.

  • propertyStatus
    public OutboxMessageStatus Status { get; init; }

    The current dispatch status of the message.

  • propertyTenantId
    public string? TenantId { get; init; }

    Optional tenant identifier for multi-tenant deployments and routing.

class

OutboxMessageBuilder<TMessage>

Ensamblado: EricksonLopez.Outbox
public sealed class OutboxMessageBuilder<TMessage> : IDisposable where TMessage : notnull
Implementa: IDisposable

Provides a fluent API for enriching an outbox message with metadata, scheduling, and transaction details before storing it.

Notas:

Usage:

await outbox
    .Publish(new OrderCreatedEvent(...))
    .WithTransaction(tx)
    .WithHeader("TenantId", "tenant-123")
    .WithDelay(TimeSpan.FromSeconds(30))
    .StoreAsync(ct);

Design note — sealed and not interface-based: `OutboxMessageBuilder<TMessage>` is intentionally `sealed` and is not backed by a public interface. This design: - Eliminates virtual dispatch in the fluent call chain (zero overhead). - Allows the internal constructor to guarantee invariants (e.g., `_outbox` is never null). - Ensures NativeAOT trimming can see all usage through the concrete type. If you need to decorate or mock the builder in tests, use `Testing.InMemoryOutboxStore` or `Testing.FakeOutboxDispatcher` instead, which capture messages without going through the real storage path. Scheduling (`deliver_at`) edge case: When using `WithDelay` or `WithDeliverAt`, ensure the scheduled time does not reach or exceed `now + OutboxRuntimeOptions.MaxMessageAge`. If it does, `StoreAsync` will throw `ArgumentOutOfRangeException` at the moment of storage to prevent silent message loss. Increase `OutboxRuntimeOptions.MaxMessageAge` to accommodate long-horizon scheduling. See `IOutboxRepository.FetchPendingAsync` for details. Type parameters: TMessage: The type of the message being enriched.

Miembros (11)

  • methodDispose
    public void Dispose()

    Inherits documentation from base type or interface.

  • methodStoreAsync
    public ValueTask StoreAsync(CancellationToken cancellationToken = default)

    Persists the enriched message atomically within the configured transaction context.

    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A `ValueTask` representing the asynchronous storage operation.

    Exceptions: ObjectDisposedException: Thrown if the builder has already been disposed (e.g., by a previous call to `StoreAsync` or an early `Dispose()`); InvalidOperationException: Thrown if a transaction context was not bound via `WithTransaction` prior to calling `StoreAsync`

  • methodWithAmbientTransaction
    public OutboxMessageBuilder<TMessage> WithAmbientTransaction(IOutboxTransactionContextAccessor accessor)

    Associates the active ambient transaction from `accessor` with the outbox message, failing closed if no ambient transaction is active.

    accessor: IOutboxTransactionContextAccessor
    The ambient transaction context accessor.

    Retorna: The current `OutboxMessageBuilder<TMessage>` instance for method chaining.

  • methodWithCausationId
    public OutboxMessageBuilder<TMessage> WithCausationId(string causationId)

    Sets the causation identifier for the message, identifying the specific operation that triggered this message.

    causationId: string
    The causation identifier to assign.

    Retorna: The current `OutboxMessageBuilder<TMessage>` instance for method chaining.

  • methodWithCompanyId
    public OutboxMessageBuilder<TMessage> WithCompanyId(string companyId)

    Sets the holding company / organization unit identifier for 1:N multi-company Row-Level Security rehydration.

    companyId: string
    The company identifier to assign.

    Retorna: The current `OutboxMessageBuilder<TMessage>` instance for method chaining.

  • methodWithCorrelationId
    public OutboxMessageBuilder<TMessage> WithCorrelationId(string correlationId)

    Sets the correlation identifier for the message, used to trace related operations across systems.

    correlationId: string
    The correlation identifier to assign.

    Retorna: The current `OutboxMessageBuilder<TMessage>` instance for method chaining.

  • methodWithDelay
    public OutboxMessageBuilder<TMessage> WithDelay(TimeSpan delay)

    Schedules the message for dispatching after the specified time delay.

    delay: TimeSpan
    The time interval to delay dispatching.

    Retorna: The current `OutboxMessageBuilder<TMessage>` instance for method chaining.

    The message will remain invisible to the dispatcher until the current UTC time is greater than or equal to the scheduled time. If the resulting delivery timestamp reaches or exceeds the configured maximum message age, `StoreAsync` will throw an exception.

  • methodWithDeliverAt
    public OutboxMessageBuilder<TMessage> WithDeliverAt(DateTimeOffset deliverAt)

    Schedules the message for dispatching at the specified absolute timestamp.

    deliverAt: DateTimeOffset
    The absolute UTC timestamp indicating when the message should become visible.

    Retorna: The current `OutboxMessageBuilder<TMessage>` instance for method chaining.

    The message will remain invisible to the dispatcher until the current UTC time is greater than or equal to the specified timestamp. If `deliverAt` reaches or exceeds the configured maximum message age, `StoreAsync` will throw an exception.

  • methodWithHeader
    public OutboxMessageBuilder<TMessage> WithHeader(string key, string value)

    Adds a custom metadata header to the message that will be propagated to the message broker.

    key: string
    The key identifying the header.
    value: string
    The value of the header.

    Retorna: The current `OutboxMessageBuilder<TMessage>` instance for method chaining.

  • methodWithTenantId
    public OutboxMessageBuilder<TMessage> WithTenantId(string tenantId)

    Sets the tenant identifier for the message for multi-tenant sharding and routing.

    tenantId: string
    The tenant identifier to assign.

    Retorna: The current `OutboxMessageBuilder<TMessage>` instance for method chaining.

  • methodWithTransaction
    public OutboxMessageBuilder<TMessage> WithTransaction(IOutboxTransactionContext transaction)

    Associates the specified database transaction with the outbox message to ensure atomic storage.

    transaction: IOutboxTransactionContext
    The transaction context to use for the storage operation.

    Retorna: The current `OutboxMessageBuilder<TMessage>` instance for method chaining.

struct

OutboxMessageMetadata

Ensamblado: EricksonLopez.Outbox.Abstractions
public readonly struct OutboxMessageMetadata

Represents key-value metadata associated with an Outbox message, optimized for raw persistence and retrieval from a data store.

Notas:

This type is a persistence-oriented representation of metadata and is intentionally distinct from `EricksonLopez.Messaging.Contracts.TransportMessageMetadata`, which models strongly typed metadata for distributed message routing and transport.

Miembros (10)

  • constructorOutboxMessageMetadata
    public OutboxMessageMetadata(string? correlationId, string? causationId, string? messageType, ReadOnlyMemory<MetadataEntry> entries = default)

    Initializes a new instance of the `OutboxMessageMetadata` struct.

    correlationId: string?
    The correlation identifier.
    causationId: string?
    The causation identifier.
    messageType: string?
    The explicit message type alias, if any.
    entries: ReadOnlyMemory<MetadataEntry>
    A memory segment of custom metadata entries.
  • constructorOutboxMessageMetadata
    public OutboxMessageMetadata(string? correlationId, string? causationId, string? messageType, string? tenantId, ReadOnlyMemory<MetadataEntry> entries = default)

    Initializes a new instance of the `OutboxMessageMetadata` struct with explicit tenant context.

    correlationId: string?
    The correlation identifier.
    causationId: string?
    The causation identifier.
    messageType: string?
    The explicit message type alias, if any.
    tenantId: string?
    The tenant or company identifier for multi-tenant isolation.
    entries: ReadOnlyMemory<MetadataEntry>
    A memory segment of custom metadata entries.
  • constructorOutboxMessageMetadata
    public OutboxMessageMetadata(string? correlationId, string? causationId, string? messageType, string? tenantId, string? companyId, ReadOnlyMemory<MetadataEntry> entries = default)

    Initializes a new instance of the `OutboxMessageMetadata` struct with explicit multi-plane tenant and company context.

    correlationId: string?
    The correlation identifier.
    causationId: string?
    The causation identifier.
    messageType: string?
    The explicit message type alias, if any.
    tenantId: string?
    The tenant identifier.
    companyId: string?
    The holding company / organization unit identifier.
    entries: ReadOnlyMemory<MetadataEntry>
    A memory segment of custom metadata entries.
  • methodGetValue
    public string? GetValue(string key)

    Retrieves the value of a metadata entry by its key.

    key: string
    The exact, case-sensitive key to search for.

    Retorna: The value associated with the specified key, or `null` if the key is not found.

  • propertyCausationId
    public string? CausationId { get; }

    Gets the causation identifier that links this message directly to the message or operation that triggered it.

  • propertyCompanyId
    public string? CompanyId { get; }

    Gets the optional holding company / organization unit identifier when `TenantId` and `CompanyId` are distinct.

  • propertyCorrelationId
    public string? CorrelationId { get; }

    Gets the correlation identifier used to trace a logical operation across multiple services.

  • propertyEntries
    public ReadOnlyMemory<MetadataEntry> Entries { get; }

    Gets the read-only memory segment of custom metadata entries (headers).

  • propertyMessageType
    public string? MessageType { get; }

    Gets the string alias representing the type of the message payload.

  • propertyTenantId
    public string? TenantId { get; }

    Gets the optional tenant or company identifier for multi-tenant isolation and Row-Level Security (RLS).

enum

OutboxMessageStatus

Ensamblado: EricksonLopez.Outbox.Abstractions
public enum OutboxMessageStatus

Represents the current processing status of an outbox message, as stored in the database.

Miembros (5)

  • fieldDeadLettered
    DeadLettered = 4

    Indicates that the message has exhausted all retry attempts and has been moved to the dead-letter queue.

  • fieldDispatched
    Dispatched = 2

    Indicates that the message was successfully dispatched to the broker.

  • fieldFailed
    Failed = 3

    Indicates that the message failed to dispatch and is scheduled for retry.

  • fieldInFlight
    InFlight = 1

    Indicates that the message has been claimed by a dispatcher and is currently being processed. This state prevents duplicate processing across concurrent dispatcher instances.

  • fieldPending
    Pending = 0

    Indicates that the message is queued and ready to be dispatched.

class

OutboxOptions

Ensamblado: EricksonLopez.Outbox
public sealed class OutboxOptions

Provides a fluent builder API for configuring the EricksonLopez.Outbox core services.

Notas:

Fluent API usage:

services.AddOutbox(options =>
{
    options.UseSerializer(new NativeAotJsonSerializer(MyGeneratedContext.Default));
    options.UseBroker<RabbitMQBrokerPublisher>();
});

Miembros (11)

  • methodConfigure
    public OutboxOptions Configure(Action<IServiceCollection> configure)

    Exposes an extension point for first-party storage engines and brokers to register additional dependency injection services during outbox configuration.

    configure: Action<IServiceCollection>
    The delegate that registers additional services into the underlying collection.

    Retorna: The current `OutboxOptions` instance for method chaining.

    WARNING: Exposes the underlying `IServiceCollection`. End users should avoid using it directly to prevent accidental tight coupling to the dependency injection framework's internals. ROADMAP-v2 — Encapsulation: Exposing `IServiceCollection` directly (even behind `[EditorBrowsable(Advanced)]`) creates an encapsulation gap: third-party integrations could register conflicting singleton services, override internal registrations, or introduce lifetime mismatches that are silent until runtime. In v2.0, consider a restricted `OutboxServicesBuilder` that exposes only approved extension points: `public OutboxOptions ConfigureServices(Action<OutboxServicesBuilder> configure)` This is deferred to avoid a breaking change in the public API surface. Exceptions: ArgumentNullException: `configure` is `null`

  • methodConfigureRuntimeOptions
    public OutboxOptions ConfigureRuntimeOptions(Action<OutboxRuntimeOptions> configure)

    Configures the runtime behavior options for the outbox.

    configure: Action<OutboxRuntimeOptions>
    The delegate used to configure the runtime options.

    Retorna: The current `OutboxOptions` instance for method chaining.

    Exceptions: ArgumentNullException: `configure` is `null`

  • methodRoute
    public BrokerRouteBuilder Route(string messageTypeAlias)

    Starts configuring a route for a specific message type.

    messageTypeAlias: string
    The alias or name of the message type.

    Retorna: A builder to specify the publisher for this route.

    Exceptions: ArgumentNullException: `messageTypeAlias` is `null`

  • methodRouteGroup
    public BrokerRouteGroupBuilder RouteGroup(IEnumerable<string> messageTypeAliases)

    Starts configuring routes for multiple message types in bulk.

    messageTypeAliases: IEnumerable<string>
    The collection of message type aliases to route.

    Retorna: A builder to specify the publisher for this route group.

    Exceptions: ArgumentNullException: `messageTypeAliases` is `null`

  • methodRouteGroup
    public BrokerRouteGroupBuilder RouteGroup(params string[] messageTypeAliases)

    Starts configuring routes for multiple message types in bulk.

    messageTypeAliases: params string[]
    The message type aliases to route.

    Retorna: A builder to specify the publisher for this route group.

    Exceptions: ArgumentNullException: `messageTypeAliases` is `null`

  • methodUseBroker
    public OutboxOptions UseBroker(Func<IServiceProvider, IBrokerPublisher> factory, RetryPolicy? retryPolicy = null, CircuitBreakerState? circuitBreaker = null)

    Configures the default broker publisher factory delegate for the outbox.

    factory: Func<IServiceProvider, IBrokerPublisher>
    A factory delegate that produces an `IBrokerPublisher` instance.
    retryPolicy: RetryPolicy?
    An optional retry policy to wrap publishing attempts.
    circuitBreaker: CircuitBreakerState?
    An optional circuit breaker state tracker.

    Retorna: The current `OutboxOptions` instance for method chaining.

  • methodUseBroker
    public OutboxOptions UseBroker(IBrokerPublisher publisher, RetryPolicy? retryPolicy = null, CircuitBreakerState? circuitBreaker = null)

    Configures the default broker publisher instance for the outbox.

    publisher: IBrokerPublisher
    The singleton broker publisher instance to register.
    retryPolicy: RetryPolicy?
    An optional retry policy to wrap publishing attempts.
    circuitBreaker: CircuitBreakerState?
    An optional circuit breaker state tracker.

    Retorna: The current `OutboxOptions` instance for method chaining.

  • methodUseBroker<TBroker>
    public OutboxOptions UseBroker<TBroker>(RetryPolicy? retryPolicy = null, CircuitBreakerState? circuitBreaker = null) where TBroker : class, IBrokerPublisher

    Configures the default broker publisher implementation for the outbox.

    retryPolicy: RetryPolicy?
    An optional retry policy to wrap publishing attempts.
    circuitBreaker: CircuitBreakerState?
    An optional circuit breaker state tracker.

    Retorna: The current `OutboxOptions` instance for method chaining.

    Type parameters: TBroker: The broker publisher implementation type.

  • methodUseSerializer
    public OutboxOptions UseSerializer(IOutboxSerializer serializer)

    Registers a specific serializer instance for use by the outbox.

    serializer: IOutboxSerializer
    The singleton serializer instance to register.

    Retorna: The current `OutboxOptions` instance for method chaining.

    Required for NativeAOT compatibility — must be a source-generated serializer. Exceptions: ArgumentNullException: `serializer` is `null`

  • methodUseSerializer<TSerializer>
    public OutboxOptions UseSerializer<TSerializer>() where TSerializer : class, IOutboxSerializer

    Registers a specific serializer type for use by the outbox.

    Retorna: The current `OutboxOptions` instance for method chaining.

    Type parameters: TSerializer: The type of the serializer to register.

  • methodUseTypeResolver
    public OutboxOptions UseTypeResolver(IOutboxMessageTypeResolver typeResolver)

    Registers a specific message type resolver instance for use by the outbox.

    typeResolver: IOutboxMessageTypeResolver
    The singleton type resolver instance to register.

    Retorna: The current `OutboxOptions` instance for method chaining.

    Exceptions: ArgumentNullException: `typeResolver` is `null`

class

OutboxPayloadTooLargeException

Ensamblado: EricksonLopez.Outbox
public sealed class OutboxPayloadTooLargeException : OutboxException
Hereda de: OutboxException

Thrown when a message payload exceeds the configured maximum payload size limit.

Miembros (3)

  • constructorOutboxPayloadTooLargeException
    public OutboxPayloadTooLargeException(int actualSize, int maxAllowedSize)

    Initializes a new instance of the `OutboxPayloadTooLargeException` class.

    actualSize: int
    The actual size of the payload in bytes.
    maxAllowedSize: int
    The maximum allowed size for the payload in bytes.
  • propertyActualSize
    public int ActualSize { get; }

    Gets the actual serialized payload size in bytes.

  • propertyMaxAllowedSize
    public int MaxAllowedSize { get; }

    Gets the configured maximum allowed payload size in bytes.

class

OutboxPublishExtensions

Ensamblado: EricksonLopez.Outbox
public static class OutboxPublishExtensions

Provides extension methods for `IOutbox` to facilitate fluent message publishing and mocking.

Miembros (5)

  • methodEnqueueAsync<TMessage>
    public static ValueTask EnqueueAsync<TMessage>(this IOutbox outbox, IEnumerable<TMessage> messages, IOutboxTransactionContext transaction, CancellationToken cancellationToken = default) where TMessage : class

    Enqueues an enumerable collection of messages directly into the outbox within the specified database transaction.

    outbox: this IOutbox
    The outbox instance.
    messages: IEnumerable<TMessage>
    The collection of messages to store.
    transaction: IOutboxTransactionContext
    The active database transaction context.
    cancellationToken: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: A task representing the asynchronous batch store operation.

    Type parameters: TMessage: The type of the messages being stored.

  • methodEnqueueAsync<TMessage>
    public static ValueTask EnqueueAsync<TMessage>(this IOutbox outbox, ReadOnlyMemory<TMessage> messages, IOutboxTransactionContext transaction, CancellationToken cancellationToken = default) where TMessage : class

    Enqueues a batch of messages directly into the outbox within the specified database transaction.

    outbox: this IOutbox
    The outbox instance.
    messages: ReadOnlyMemory<TMessage>
    A memory region containing the messages to store.
    transaction: IOutboxTransactionContext
    The active database transaction context.
    cancellationToken: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: A task representing the asynchronous batch store operation.

    Type parameters: TMessage: The type of the messages being stored.

  • methodEnqueueAsync<TMessage>
    public static ValueTask EnqueueAsync<TMessage>(this IOutbox outbox, TMessage message, IOutboxTransactionContext transaction, CancellationToken cancellationToken = default) where TMessage : class

    Enqueues an event or message directly into the outbox within the specified database transaction.

    outbox: this IOutbox
    The outbox instance.
    message: TMessage
    The message instance to store.
    transaction: IOutboxTransactionContext
    The active database transaction context.
    cancellationToken: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: A task representing the asynchronous store operation.

    Type parameters: TMessage: The type of the message being stored.

  • methodEnqueueAsync<TMessage>
    public static ValueTask EnqueueAsync<TMessage>(this IOutbox outbox, TMessage message, IOutboxTransactionContext transaction, OutboxMessageMetadata metadata, DateTimeOffset? deliverAt = null, CancellationToken cancellationToken = default) where TMessage : class

    Enqueues an event or message with explicit metadata and scheduling directly into the outbox.

    outbox: this IOutbox
    The outbox instance.
    message: TMessage
    The message instance to store.
    transaction: IOutboxTransactionContext
    The active database transaction context.
    metadata: OutboxMessageMetadata
    The metadata associated with the message.
    deliverAt: DateTimeOffset?
    An optional future timestamp indicating when the message should be dispatched.
    cancellationToken: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: A task representing the asynchronous store operation.

    Type parameters: TMessage: The type of the message being stored.

  • methodPublish<TMessage>
    public static OutboxMessageBuilder<TMessage> Publish<TMessage>(this IOutbox outbox, TMessage message) where TMessage : notnull

    Begins a fluent message-building chain for enriching a message before persisting it.

    outbox: this IOutbox
    The outbox instance.
    message: TMessage
    The initial message payload to begin enriching.

    Retorna: A fluent builder instance to configure transaction, delay, and metadata.

    Type parameters: TMessage: The type of the message being built.

class

OutboxRuntimeException

Ensamblado: EricksonLopez.Outbox
public sealed class OutboxRuntimeException : OutboxException
Hereda de: OutboxException

Thrown when an unexpected error occurs during outbox runtime operations (e.g., polling, dispatching).

Miembros (2)

  • constructorOutboxRuntimeException
    public OutboxRuntimeException(string message)

    Initializes a new instance of the `OutboxRuntimeException` class with a specified error message.

    message: string
    The message that describes the runtime error.
  • constructorOutboxRuntimeException
    public OutboxRuntimeException(string message, Exception innerException)

    Initializes a new instance of the `OutboxRuntimeException` class with a specified error message and a reference to the inner exception that is the cause of this exception.

    message: string
    The message that describes the runtime error.
    innerException: Exception
    The inner exception.
class

OutboxRuntimeOptions

Ensamblado: EricksonLopez.Outbox
public sealed class OutboxRuntimeOptions

Represents the runtime configuration options governing message processing in the outbox.

Miembros (14)

  • propertyDeleteOnDispatch
    public bool DeleteOnDispatch { get; set; }

    Gets or sets a value indicating whether dispatched messages are physically deleted from the outbox table.

  • propertyIncludeMessageTypeTag
    public bool IncludeMessageTypeTag { get; set; }

    Gets or sets a value indicating whether to include the `messaging.message.type` tag on OpenTelemetry metrics instruments (counters, histograms).

  • propertyInstanceId
    public string InstanceId { get; internal set; }

    Gets the unique identifier for this specific instance of the outbox runtime.

  • propertyLargeTableThreshold
    public int LargeTableThreshold { get; set; }

    Gets or sets the threshold (number of estimated rows) above which exact COUNT(*) is bypassed in favor of catalog estimates.

  • propertyMaxBackoffSeconds
    public int MaxBackoffSeconds { get; set; }

    Gets or sets the maximum exponential backoff delay, in seconds, for failed messages awaiting retry.

  • propertyMaxHeaderSizeInBytes
    public int MaxHeaderSizeInBytes { get; set; }

    Gets or sets the maximum allowed size, in bytes, for the serialized metadata headers of a message.

  • propertyMaxMessageAge
    public TimeSpan MaxMessageAge { get; set; }

    Gets or sets the maximum age of a message before it is eligible for cleanup or archival.

  • propertyMaxPayloadSizeInBytes
    public int MaxPayloadSizeInBytes { get; set; }

    Gets or sets the maximum allowed size, in bytes, for an individual message payload.

  • propertyMaxRetryCount
    public int MaxRetryCount { get; set; }

    Gets or sets the maximum number of retry and lease-reclamation attempts before a message is permanently dead-lettered to prevent infinite crash loops. Default is 10.

  • propertyMaxStoreRatePerSecond
    public int MaxStoreRatePerSecond { get; set; }

    Gets or sets the maximum number of messages that can be stored per second via `IOutbox.StoreAsync`. A value of `0` means no limit (unbounded).

  • propertyReclaimBatchLimit
    public int ReclaimBatchLimit { get; set; }

    Gets or sets the maximum number of stale messages (state=1 InFlight) reclaimed per reclaim cycle.

  • propertySchemaName
    public string SchemaName { get; set; }

    Gets or sets the database schema name where the outbox tables reside.

  • propertyTableName
    public string TableName { get; set; }

    Gets or sets the base name of the outbox messages table.

  • propertyThrowOnUnregisteredType
    public bool ThrowOnUnregisteredType { get; set; }

    Gets or sets a value indicating whether to throw an exception if an unregistered message type is encountered.

class

OutboxSerializationException

Ensamblado: EricksonLopez.Outbox
public sealed class OutboxSerializationException : OutboxException
Hereda de: OutboxException

Thrown when the serialization of a message payload fails during the outbox processing.

Miembros (2)

  • constructorOutboxSerializationException
    public OutboxSerializationException(string messageTypeAlias, Exception innerException)

    Initializes a new instance of the `OutboxSerializationException` class with the specified message type alias and the inner exception that caused this exception.

    messageTypeAlias: string
    The alias associated with the message type.
    innerException: Exception
    The exception that is the cause of the current exception.
  • propertyMessageTypeAlias
    public string? MessageTypeAlias { get; }

    Gets the alias of the message type that failed to serialize.

class

OutboxTypeNotRegisteredException

Ensamblado: EricksonLopez.Outbox
public sealed class OutboxTypeNotRegisteredException : OutboxException
Hereda de: OutboxException

Thrown when an outbox message type is not registered in the type resolver and strict type mapping is enforced.

Miembros (3)

  • constructorOutboxTypeNotRegisteredException
    public OutboxTypeNotRegisteredException(Type messageType)

    Initializes a new instance of the `OutboxTypeNotRegisteredException` class for the specified message type.

    messageType: Type
    The type of the message that was not registered.
  • constructorOutboxTypeNotRegisteredException
    public OutboxTypeNotRegisteredException(Type messageType, Exception innerException)

    Initializes a new instance of the `OutboxTypeNotRegisteredException` class for the specified message type with a reference to the inner exception that caused this exception.

    messageType: Type
    The type of the message that was not registered.
    innerException: Exception
    The exception that is the cause of the current exception.
  • propertyMessageType
    public Type MessageType { get; }

    Gets the type of the outbox message that failed to resolve.

record

Publisher

Ensamblado: EricksonLopez.Outbox
public readonly record struct Publisher(string Id, string Name, DateTimeOffset RegisteredAt)

Represents a logical publisher identity within the outbox ecosystem.

Notas:

Identifies which specific publisher instance or node is responsible for dispatching a given batch of messages in multi-publisher scenarios.

Miembros (6)

  • constructorPublisher
    public Publisher(string Id, string Name, DateTimeOffset RegisteredAt)

    Initializes a new instance of Publisher.

    Id: string
    The unique identifier of the publisher instance.
    Name: string
    The human-readable name or role of the publisher.
    RegisteredAt: DateTimeOffset
    The exact date and time the publisher was registered or started.

    Identifies which specific publisher instance or node is responsible for dispatching a given batch of messages in multi-publisher scenarios.

  • methodCreate
    public static Publisher Create(string name)

    Creates a new publisher with a unique identifier and the current timestamp.

    name: string
    The human-readable name of the publisher.

    Retorna: A new `Publisher` instance with an auto-generated unique ID.

    Exceptions: ArgumentException: `name` is `null` or empty

  • propertyId
    public string Id { get; init; }

    The unique identifier of the publisher instance.

  • propertyName
    public string Name { get; init; }

    The human-readable name or role of the publisher.

  • propertyRegisteredAt
    public DateTimeOffset RegisteredAt { get; init; }

    The exact date and time the publisher was registered or started.

  • fieldNone
    public static readonly Publisher None

    Represents a null-object publisher for scenarios where publisher identity is not required.

EricksonLopez.Outbox.Analyzers#

9
class

OutboxInfiniteRetriesCodeFixProvider

Ensamblado: EricksonLopez.Outbox.Analyzers
public sealed class OutboxInfiniteRetriesCodeFixProvider : CodeFixProvider
Hereda de: CodeFixProvider

Provides a code fix provider for OUTBOX004 that replaces non-positive or excessive retry attempts with a default count.

Miembros (3)

  • methodGetFixAllProvider
    public override FixAllProvider GetFixAllProvider()

    Inherits documentation from base type or interface.

  • methodRegisterCodeFixesAsync
    public override async Task RegisterCodeFixesAsync(CodeFixContext context)

    Inherits documentation from base type or interface.

    context: CodeFixContext
  • propertyFixableDiagnosticIds
    public override ImmutableArray<string> FixableDiagnosticIds { get; }

    Inherits documentation from base type or interface.

class

OutboxIntegrationEventAliasCodeFixProvider

Ensamblado: EricksonLopez.Outbox.Analyzers
public sealed class OutboxIntegrationEventAliasCodeFixProvider : CodeFixProvider
Hereda de: CodeFixProvider

Provides a code fix provider for OUTBOX006 that adds a stable `[OutboxMessage]` attribute to integration events.

Miembros (3)

  • methodGetFixAllProvider
    public override FixAllProvider GetFixAllProvider()

    Inherits documentation from base type or interface.

  • methodRegisterCodeFixesAsync
    public override async Task RegisterCodeFixesAsync(CodeFixContext context)

    Inherits documentation from base type or interface.

    context: CodeFixContext
  • propertyFixableDiagnosticIds
    public override ImmutableArray<string> FixableDiagnosticIds { get; }

    Inherits documentation from base type or interface.

class

OutboxMessageAnalyzer

Ensamblado: EricksonLopez.Outbox.Analyzers
public sealed class OutboxMessageAnalyzer : DiagnosticAnalyzer
Hereda de: DiagnosticAnalyzer

Provides a Roslyn diagnostic analyzer that enforces Outbox design patterns and invariants at compile time.

Miembros (26)

  • methodInitialize
    public override void Initialize(AnalysisContext context)

    Inherits documentation from base type or interface.

    context: AnalysisContext
  • propertySupportedDiagnostics
    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }

    Inherits documentation from base type or interface.

  • fieldAbandonedBuilderDiagnosticId
    public const string AbandonedBuilderDiagnosticId

    Defines the diagnostic identifier for abandoned message builder instances.

  • fieldAbandonedBuilderRule
    public static readonly DiagnosticDescriptor AbandonedBuilderRule

    Defines the diagnostic rule descriptor for abandoned message builder instances.

  • fieldDefaultDispatchResultDiagnosticId
    public const string DefaultDispatchResultDiagnosticId

    Defines the diagnostic identifier for default dispatch result returns.

  • fieldDefaultDispatchResultRule
    public static readonly DiagnosticDescriptor DefaultDispatchResultRule

    Defines the diagnostic rule descriptor for default dispatch result returns.

  • fieldInfiniteRetriesDiagnosticId
    public const string InfiniteRetriesDiagnosticId

    Defines the diagnostic identifier for infinite retry configurations.

  • fieldInfiniteRetriesRule
    public static readonly DiagnosticDescriptor InfiniteRetriesRule

    Defines the diagnostic rule descriptor for infinite retry configurations.

  • fieldMissingAliasDiagnosticId
    public const string MissingAliasDiagnosticId

    Defines the diagnostic identifier for missing message aliases.

  • fieldMissingAliasRule
    public static readonly DiagnosticDescriptor MissingAliasRule

    Defines the diagnostic rule descriptor for missing message aliases.

  • fieldMissingIdDiagnosticId
    public const string MissingIdDiagnosticId

    Defines the diagnostic identifier for missing message identifier properties.

  • fieldMissingIdRule
    public static readonly DiagnosticDescriptor MissingIdRule

    Defines the diagnostic rule descriptor for missing message identifier properties.

  • fieldMissingJsonSerializableDiagnosticId
    public const string MissingJsonSerializableDiagnosticId

    Defines the diagnostic identifier for unregistered AOT JSON types.

  • fieldMissingJsonSerializableRule
    public static readonly DiagnosticDescriptor MissingJsonSerializableRule

    Defines the diagnostic rule descriptor for unregistered AOT JSON types.

  • fieldMissingOutboxMessageAttributeDiagnosticId
    public const string MissingOutboxMessageAttributeDiagnosticId

    Defines the diagnostic identifier for missing integration event outbox attributes.

  • fieldMissingOutboxMessageAttributeRule
    public static readonly DiagnosticDescriptor MissingOutboxMessageAttributeRule

    Defines the diagnostic rule descriptor for missing integration event outbox attributes.

  • fieldNonIdempotentConsumerDiagnosticId
    public const string NonIdempotentConsumerDiagnosticId

    Defines the diagnostic identifier for non-idempotent consumers.

  • fieldNonIdempotentConsumerRule
    public static readonly DiagnosticDescriptor NonIdempotentConsumerRule

    Defines the diagnostic rule descriptor for non-idempotent consumers.

  • fieldNullTransactionDiagnosticId
    public const string NullTransactionDiagnosticId

    Defines the diagnostic identifier for null transaction invocations.

  • fieldNullTransactionRule
    public static readonly DiagnosticDescriptor NullTransactionRule

    Defines the diagnostic rule descriptor for null transaction invocations.

  • fieldSerializationConfigDiagnosticId
    public const string SerializationConfigDiagnosticId

    Defines the diagnostic identifier for missing serializer configurations.

  • fieldSerializationConfigRule
    public static readonly DiagnosticDescriptor SerializationConfigRule

    Defines the diagnostic rule descriptor for missing serializer configurations.

  • fieldStaleLeaseTimeoutDiagnosticId
    public const string StaleLeaseTimeoutDiagnosticId

    Defines the diagnostic identifier for low reclaim/stale lease timeout configurations.

  • fieldStaleLeaseTimeoutRule
    public static readonly DiagnosticDescriptor StaleLeaseTimeoutRule

    Defines the diagnostic rule descriptor for low reclaim/stale lease timeout configurations.

  • fieldZeroMaxRetriesDiagnosticId
    public const string ZeroMaxRetriesDiagnosticId

    Defines the diagnostic identifier for zero maximum retries configurations.

  • fieldZeroMaxRetriesRule
    public static readonly DiagnosticDescriptor ZeroMaxRetriesRule

    Defines the diagnostic rule descriptor for zero maximum retries configurations.

class

OutboxMissingAliasCodeFixProvider

Ensamblado: EricksonLopez.Outbox.Analyzers
public sealed class OutboxMissingAliasCodeFixProvider : CodeFixProvider
Hereda de: CodeFixProvider

Provides a code fix provider for OUTBOX002 that generates a stable `[OutboxMessage]` attribute from the class name.

Miembros (3)

  • methodGetFixAllProvider
    public override FixAllProvider GetFixAllProvider()

    Inherits documentation from base type or interface.

  • methodRegisterCodeFixesAsync
    public override async Task RegisterCodeFixesAsync(CodeFixContext context)

    Inherits documentation from base type or interface.

    context: CodeFixContext
  • propertyFixableDiagnosticIds
    public override ImmutableArray<string> FixableDiagnosticIds { get; }

    Inherits documentation from base type or interface.

class

OutboxMissingIdCodeFixProvider

Ensamblado: EricksonLopez.Outbox.Analyzers
public sealed class OutboxMissingIdCodeFixProvider : CodeFixProvider
Hereda de: CodeFixProvider

Provides a code fix provider for OUTBOX001 that adds a missing `Guid Id` property to message types.

Miembros (3)

  • methodGetFixAllProvider
    public override FixAllProvider GetFixAllProvider()

    Inherits documentation from base type or interface.

  • methodRegisterCodeFixesAsync
    public override async Task RegisterCodeFixesAsync(CodeFixContext context)

    Inherits documentation from base type or interface.

    context: CodeFixContext
  • propertyFixableDiagnosticIds
    public override ImmutableArray<string> FixableDiagnosticIds { get; }

    Inherits documentation from base type or interface.

class

OutboxMissingInboxConsumerCodeFixProvider

Ensamblado: EricksonLopez.Outbox.Analyzers
public sealed class OutboxMissingInboxConsumerCodeFixProvider : CodeFixProvider
Hereda de: CodeFixProvider

Provides a code fix provider for OUTBOX003 that adds the missing `[InboxConsumer]` attribute to consumers.

Miembros (3)

  • methodGetFixAllProvider
    public override FixAllProvider GetFixAllProvider()

    Inherits documentation from base type or interface.

  • methodRegisterCodeFixesAsync
    public override async Task RegisterCodeFixesAsync(CodeFixContext context)

    Inherits documentation from base type or interface.

    context: CodeFixContext
  • propertyFixableDiagnosticIds
    public override ImmutableArray<string> FixableDiagnosticIds { get; }

    Inherits documentation from base type or interface.

class

OutboxMissingSerializerCodeFixProvider

Ensamblado: EricksonLopez.Outbox.Analyzers
public sealed class OutboxMissingSerializerCodeFixProvider : CodeFixProvider
Hereda de: CodeFixProvider

Provides a code fix provider for OUTBOX005 that configures a serializer in the OutboxOptions setup.

Miembros (3)

  • methodGetFixAllProvider
    public override FixAllProvider GetFixAllProvider()

    Inherits documentation from base type or interface.

  • methodRegisterCodeFixesAsync
    public override async Task RegisterCodeFixesAsync(CodeFixContext context)

    Inherits documentation from base type or interface.

    context: CodeFixContext
  • propertyFixableDiagnosticIds
    public override ImmutableArray<string> FixableDiagnosticIds { get; }

    Inherits documentation from base type or interface.

class

OutboxNullTransactionCodeFixProvider

Ensamblado: EricksonLopez.Outbox.Analyzers
public sealed class OutboxNullTransactionCodeFixProvider : CodeFixProvider
Hereda de: CodeFixProvider

Provides a code fix provider for OUTBOX007 that replaces a null transaction argument with a transaction identifier.

Miembros (3)

  • methodGetFixAllProvider
    public override FixAllProvider GetFixAllProvider()

    Inherits documentation from base type or interface.

  • methodRegisterCodeFixesAsync
    public override async Task RegisterCodeFixesAsync(CodeFixContext context)

    Inherits documentation from base type or interface.

    context: CodeFixContext
  • propertyFixableDiagnosticIds
    public override ImmutableArray<string> FixableDiagnosticIds { get; }

    Inherits documentation from base type or interface.

class

TransactionRequiredAnalyzer

Ensamblado: EricksonLopez.Outbox.Analyzers
public class TransactionRequiredAnalyzer : DiagnosticAnalyzer
Hereda de: DiagnosticAnalyzer

Provides a Roslyn diagnostic analyzer that ensures message store calls from the fluent builder are associated with a transaction.

Miembros (3)

  • methodInitialize
    public override void Initialize(AnalysisContext context)

    Inherits documentation from base type or interface.

    context: AnalysisContext
  • propertySupportedDiagnostics
    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }

    Inherits documentation from base type or interface.

  • fieldDiagnosticId
    public const string DiagnosticId

    Defines the diagnostic identifier for missing transaction calls in builder chains.

EricksonLopez.Outbox.Aspire#

1
class

OutboxAspireExtensions

Ensamblado: EricksonLopez.Outbox.Aspire
public static class OutboxAspireExtensions

Provides extension methods for integrating the outbox engine with .NET Aspire host applications.

Miembros (1)

  • methodAddOutbox
    public static IHostApplicationBuilder AddOutbox(this IHostApplicationBuilder builder, Action<OutboxOptions>? configure = null)

    Registers EricksonLopez.Outbox services into the .NET Aspire host builder, automatically configuring OpenTelemetry metrics, distributed tracing, and health checks.

    builder: this IHostApplicationBuilder
    The Aspire host application builder.
    configure: Action<OutboxOptions>?
    Configuration delegate for outbox options.

    Retorna: The host application builder for chaining.

    Exceptions: ArgumentNullException: `builder` is `null`

EricksonLopez.Outbox.Brighter#

2
class

BrighterOutboxServiceCollectionExtensions

Ensamblado: EricksonLopez.Outbox.Brighter
public static class BrighterOutboxServiceCollectionExtensions

Provides extension methods for registering the outbox message producer for Brighter.

Miembros (1)

  • methodAddOutboxBrighterProducer
    public static IServiceCollection AddOutboxBrighterProducer(this IServiceCollection services)

    Registers the `OutboxMessageProducer` into the dependency injection container.

    services: this IServiceCollection
    The service collection.

    Retorna: The modified service collection.

    Exceptions: ArgumentNullException: `services` is `null`

class

OutboxMessageProducer

Ensamblado: EricksonLopez.Outbox.Brighter
public sealed class OutboxMessageProducer : IAmAMessageProducerAsync
Implementa: IAmAMessageProducerAsync

Provides a message producer adapter for Paramore.Brighter that writes outgoing messages into `IOutbox`.

Miembros (9)

  • constructorOutboxMessageProducer
    public OutboxMessageProducer(IOutbox outbox, IOutboxTransactionContext? transactionContext = null)

    Initializes a new instance of the `OutboxMessageProducer` class.

    outbox: IOutbox
    The outbox instance.
    transactionContext: IOutboxTransactionContext?
    The active transaction context.

    Exceptions: ArgumentNullException: `outbox` is `null`

  • methodDispose
    public void Dispose()

    Inherits documentation from base type or interface.

  • methodDisposeAsync
    public ValueTask DisposeAsync()

    Inherits documentation from base type or interface.

  • methodSendAsync
    public async Task SendAsync(Message message, CancellationToken cancellationToken = default)

    Inherits documentation from base type or interface.

    message: Message
    cancellationToken: CancellationToken
  • methodSendWithDelayAsync
    public async Task SendWithDelayAsync(Message message, TimeSpan? delay = null, CancellationToken cancellationToken = default)

    Inherits documentation from base type or interface.

    message: Message
    delay: TimeSpan?
    cancellationToken: CancellationToken
  • propertyPublication
    public Publication Publication { get; set; }

    Inherits documentation from base type or interface.

  • propertyRequestContext
    public IRequestContext? RequestContext { get; set; }

    Inherits documentation from base type or interface.

  • propertyScheduler
    public IAmAMessageScheduler? Scheduler { get; set; }

    Inherits documentation from base type or interface.

  • propertySpan
    public Activity? Span { get; set; }

    Inherits documentation from base type or interface.

EricksonLopez.Outbox.Brokers.AwsSqs#

1
class

AwsSqsBrokerPublisher

Ensamblado: EricksonLopez.Outbox.Brokers.AwsSqs
public sealed class AwsSqsBrokerPublisher : IBrokerPublisher
Implementa: IBrokerPublisher

Provides a broker publisher implementation that dispatches outbox messages to Amazon Simple Queue Service (SQS).

Miembros (4)

  • constructorAwsSqsBrokerPublisher
    public AwsSqsBrokerPublisher(IAmazonSQS sqsClient, IOutboxSerializer serializer, string queueUrl)

    Initializes a new instance of the `AwsSqsBrokerPublisher` class.

    sqsClient: IAmazonSQS
    The Amazon SQS client that communicates with the service.
    serializer: IOutboxSerializer
    The serializer that converts message payloads to byte arrays.
    queueUrl: string
    The URL of the target SQS queue.

    Exceptions: ArgumentNullException: `sqsClient`, `serializer`, or `queueUrl` is `null`

  • methodPublishAsync<T>
    public async ValueTask<DispatchResult> PublishAsync<T>(MessageEnvelope<T> message, DispatchContext context) where T : notnull

    Inherits documentation from base type or interface.

    message: MessageEnvelope<T>
    context: DispatchContext
  • methodPublishBatchAsync<T>
    public async ValueTask<IReadOnlyList<DispatchResult>> PublishBatchAsync<T>(IReadOnlyList<MessageEnvelope<T>> messages, DispatchContext context) where T : notnull

    Inherits documentation from base type or interface.

    messages: IReadOnlyList<MessageEnvelope<T>>
    context: DispatchContext
  • methodPublishRawAsync
    public async ValueTask<DispatchResult> PublishRawAsync(OutboxMessage message, OutboxMessageMetadata metadata, DispatchContext context)

    Publishes a raw serialized outbox message as-is.

    message: OutboxMessage
    The raw outbox message to publish.
    metadata: OutboxMessageMetadata
    The metadata associated with the message.
    context: DispatchContext
    The context governing the dispatch operation, including cancellation tokens.

    Retorna: A task that represents the asynchronous dispatch operation, containing the `DispatchResult`.

    Used by the Dispatcher which works with pre-serialized payloads, avoiding runtime generics and reflection for NativeAOT compatibility. DispatchResult contract for implementers: **Scenario**: **Return value**: - **Message published successfully**: **`DispatchResult.Ok()`**: - **Transient / recoverable failure (network timeout, broker unreachable, rate-limited)**: **`DispatchResult.FailAndRetry(exception)`**: - **Fatal / unrecoverable failure (schema mismatch, serialization error, message too large for broker, authorization denied)**: **`DispatchResult.FailFatal(exception)`**: Do NOT throw exceptions here. Thrown exceptions are treated as fatal failures by the dispatcher (equivalent to `DispatchResult.FailFatal`). Always catch broker exceptions and map them to the appropriate `DispatchResult`. Do NOT return `default(DispatchResult)`. The default value of the struct (`Success=false, ShouldRetry=false, Error=null`) is an invalid state that will cause the dispatcher to dead-letter the message with a misleading "no error" state. Always use one of the factory methods: `DispatchResult.Ok()`, `DispatchResult.FailAndRetry(ex)`, or `DispatchResult.FailFatal(ex)`. The dispatcher wraps calls to the publisher with a retry interceptor, which automatically retries `FailAndRetry` results with exponential backoff. Returning `FailFatal` bypasses retry and dead-letters the message immediately. OpenTelemetry — `messaging.system` tag requirement: The outbox core sets `messaging.system = "outbox"` as a default on the dispatch Activity. Broker implementers MUST override this tag with the actual broker name: `System.Diagnostics.Activity.Current?.SetTag("messaging.system", "rabbitmq"); // or "kafka", "azure_service_bus", etc.` This is required by the OpenTelemetry Messaging Semantic Conventions (v1.26+): https://opentelemetry.io/docs/specs/semconv/messaging/messaging-spans/#messaging-attributes

EricksonLopez.Outbox.Brokers.AzureEventHubs#

1
class

AzureEventHubsBrokerPublisher

Ensamblado: EricksonLopez.Outbox.Brokers.AzureEventHubs
public sealed class AzureEventHubsBrokerPublisher : IBrokerPublisher, ITypedBrokerPublisher
Implementa: IBrokerPublisher, ITypedBrokerPublisher

Provides a broker publisher implementation that dispatches outbox messages to Azure Event Hubs.

Miembros (5)

  • constructorAzureEventHubsBrokerPublisher
    public AzureEventHubsBrokerPublisher(EventHubProducerClient producerClient, IOutboxSerializer? serializer = null)

    Initializes a new instance of the `AzureEventHubsBrokerPublisher` class.

    producerClient: EventHubProducerClient
    The Azure Event Hubs producer client.
    serializer: IOutboxSerializer?
    The optional serializer for strongly typed publishing.

    Exceptions: ArgumentNullException: `producerClient` is `null`

  • methodPublishAsync<T>
    public async ValueTask<DispatchResult> PublishAsync<T>(MessageEnvelope<T> message, DispatchContext context) where T : notnull

    Publishes a strongly-typed message envelope to the underlying broker.

    message: MessageEnvelope<T>
    The message envelope containing payload and metadata.
    context: DispatchContext
    The context governing the dispatch operation.

    Retorna: A task representing the asynchronous operation, containing the `DispatchResult`.

    Type parameters: T: The type of the message payload.

  • methodPublishBatchAsync<T>
    public async ValueTask<IReadOnlyList<DispatchResult>> PublishBatchAsync<T>(IReadOnlyList<MessageEnvelope<T>> messages, DispatchContext context) where T : notnull

    Publishes a batch of strongly-typed message envelopes to the underlying broker.

    messages: IReadOnlyList<MessageEnvelope<T>>
    The read-only list of message envelopes to publish.
    context: DispatchContext
    The context governing the dispatch operation.

    Retorna: A task representing the asynchronous operation, containing the list of dispatch results.

    Type parameters: T: The type of the message payload.

  • methodPublishRawAsync
    public async ValueTask<DispatchResult> PublishRawAsync(OutboxMessage message, OutboxMessageMetadata metadata, DispatchContext context)

    Publishes a raw serialized outbox message as-is.

    message: OutboxMessage
    The raw outbox message to publish.
    metadata: OutboxMessageMetadata
    The metadata associated with the message.
    context: DispatchContext
    The context governing the dispatch operation, including cancellation tokens.

    Retorna: A task that represents the asynchronous dispatch operation, containing the `DispatchResult`.

    Used by the Dispatcher which works with pre-serialized payloads, avoiding runtime generics and reflection for NativeAOT compatibility. DispatchResult contract for implementers: **Scenario**: **Return value**: - **Message published successfully**: **`DispatchResult.Ok()`**: - **Transient / recoverable failure (network timeout, broker unreachable, rate-limited)**: **`DispatchResult.FailAndRetry(exception)`**: - **Fatal / unrecoverable failure (schema mismatch, serialization error, message too large for broker, authorization denied)**: **`DispatchResult.FailFatal(exception)`**: Do NOT throw exceptions here. Thrown exceptions are treated as fatal failures by the dispatcher (equivalent to `DispatchResult.FailFatal`). Always catch broker exceptions and map them to the appropriate `DispatchResult`. Do NOT return `default(DispatchResult)`. The default value of the struct (`Success=false, ShouldRetry=false, Error=null`) is an invalid state that will cause the dispatcher to dead-letter the message with a misleading "no error" state. Always use one of the factory methods: `DispatchResult.Ok()`, `DispatchResult.FailAndRetry(ex)`, or `DispatchResult.FailFatal(ex)`. The dispatcher wraps calls to the publisher with a retry interceptor, which automatically retries `FailAndRetry` results with exponential backoff. Returning `FailFatal` bypasses retry and dead-letters the message immediately. OpenTelemetry — `messaging.system` tag requirement: The outbox core sets `messaging.system = "outbox"` as a default on the dispatch Activity. Broker implementers MUST override this tag with the actual broker name: `System.Diagnostics.Activity.Current?.SetTag("messaging.system", "rabbitmq"); // or "kafka", "azure_service_bus", etc.` This is required by the OpenTelemetry Messaging Semantic Conventions (v1.26+): https://opentelemetry.io/docs/specs/semconv/messaging/messaging-spans/#messaging-attributes

  • propertyBrokerSystemName
    public string BrokerSystemName { get; }

    Gets the OpenTelemetry `messaging.system` attribute value for this broker implementation.

    The outbox dispatcher reads this value to set the `messaging.system` tag on the dispatch `Diagnostics.Activity`, conforming to the OpenTelemetry Messaging Semantic Conventions (v1.26+). See: https://opentelemetry.io/docs/specs/semconv/messaging/messaging-spans/ Override this property in your broker publisher to return the canonical OTel system name: **Broker**: **Return value**: - **RabbitMQ**: **`"rabbitmq"`**: - **Apache Kafka**: **`"kafka"`**: - **Azure Service Bus**: **`"azure_service_bus"`**: - **Amazon SQS**: **`"aws_sqs"`**: - **Google Pub/Sub**: **`"gcp_pubsub"`**: - **NATS**: **`"nats"`**: - **Redis Streams**: **`"redis"`**: The default implementation returns `"outbox"` as a fallback sentinel value. The dispatcher will use this value automatically — broker publishers no longer need to call `Activity.Current?.SetTag("messaging.system", ...)` manually.

EricksonLopez.Outbox.Brokers.AzureServiceBus#

1
class

AzureServiceBusBrokerPublisher

Ensamblado: EricksonLopez.Outbox.Brokers.AzureServiceBus
public sealed class AzureServiceBusBrokerPublisher : IBrokerPublisher
Implementa: IBrokerPublisher

Provides a broker publisher implementation that dispatches outbox messages to Azure Service Bus.

Miembros (4)

  • constructorAzureServiceBusBrokerPublisher
    public AzureServiceBusBrokerPublisher(ServiceBusSender sender, IOutboxSerializer serializer)

    Initializes a new instance of the `AzureServiceBusBrokerPublisher` class.

    sender: ServiceBusSender
    The Azure Service Bus sender client.
    serializer: IOutboxSerializer
    The serializer that converts message payloads to byte arrays.

    Exceptions: ArgumentNullException: `sender` or `serializer` is `null`

  • methodPublishAsync<T>
    public async ValueTask<DispatchResult> PublishAsync<T>(MessageEnvelope<T> message, DispatchContext context) where T : notnull

    Inherits documentation from base type or interface.

    message: MessageEnvelope<T>
    context: DispatchContext
  • methodPublishBatchAsync<T>
    public async ValueTask<IReadOnlyList<DispatchResult>> PublishBatchAsync<T>(IReadOnlyList<MessageEnvelope<T>> messages, DispatchContext context) where T : notnull

    Inherits documentation from base type or interface.

    messages: IReadOnlyList<MessageEnvelope<T>>
    context: DispatchContext
  • methodPublishRawAsync
    public async ValueTask<DispatchResult> PublishRawAsync(OutboxMessage message, OutboxMessageMetadata metadata, DispatchContext context)

    Publishes a raw serialized outbox message as-is.

    message: OutboxMessage
    The raw outbox message to publish.
    metadata: OutboxMessageMetadata
    The metadata associated with the message.
    context: DispatchContext
    The context governing the dispatch operation, including cancellation tokens.

    Retorna: A task that represents the asynchronous dispatch operation, containing the `DispatchResult`.

    Used by the Dispatcher which works with pre-serialized payloads, avoiding runtime generics and reflection for NativeAOT compatibility. DispatchResult contract for implementers: **Scenario**: **Return value**: - **Message published successfully**: **`DispatchResult.Ok()`**: - **Transient / recoverable failure (network timeout, broker unreachable, rate-limited)**: **`DispatchResult.FailAndRetry(exception)`**: - **Fatal / unrecoverable failure (schema mismatch, serialization error, message too large for broker, authorization denied)**: **`DispatchResult.FailFatal(exception)`**: Do NOT throw exceptions here. Thrown exceptions are treated as fatal failures by the dispatcher (equivalent to `DispatchResult.FailFatal`). Always catch broker exceptions and map them to the appropriate `DispatchResult`. Do NOT return `default(DispatchResult)`. The default value of the struct (`Success=false, ShouldRetry=false, Error=null`) is an invalid state that will cause the dispatcher to dead-letter the message with a misleading "no error" state. Always use one of the factory methods: `DispatchResult.Ok()`, `DispatchResult.FailAndRetry(ex)`, or `DispatchResult.FailFatal(ex)`. The dispatcher wraps calls to the publisher with a retry interceptor, which automatically retries `FailAndRetry` results with exponential backoff. Returning `FailFatal` bypasses retry and dead-letters the message immediately. OpenTelemetry — `messaging.system` tag requirement: The outbox core sets `messaging.system = "outbox"` as a default on the dispatch Activity. Broker implementers MUST override this tag with the actual broker name: `System.Diagnostics.Activity.Current?.SetTag("messaging.system", "rabbitmq"); // or "kafka", "azure_service_bus", etc.` This is required by the OpenTelemetry Messaging Semantic Conventions (v1.26+): https://opentelemetry.io/docs/specs/semconv/messaging/messaging-spans/#messaging-attributes

EricksonLopez.Outbox.Brokers.GooglePubSub#

1
class

GooglePubSubBrokerPublisher

Ensamblado: EricksonLopez.Outbox.Brokers.GooglePubSub
public sealed class GooglePubSubBrokerPublisher : IBrokerPublisher
Implementa: IBrokerPublisher

Provides a broker publisher implementation that dispatches outbox messages to Google Cloud Pub/Sub using the official Google.Cloud.PubSub.V1 client.

Notas:

Design decisions: - Topic name is derived from the message type alias to allow environment-specific topic naming conventions. - Message attributes provide metadata (CorrelationId, CausationId, MessageType). Attributes are indexed by Pub/Sub and support subscription filter expressions. - PublishRawAsync sends the pre-serialized payload directly — avoids double serialization. - Ordering keys are not set by default; enable them per-topic if strict ordering is required. Trade-off: + Fully managed — no infrastructure to maintain. + At-least-once delivery with configurable retention. - Topic must be pre-created (Infrastructure as Code ownership).

Miembros (4)

  • constructorGooglePubSubBrokerPublisher
    public GooglePubSubBrokerPublisher(PublisherServiceApiClient client, string projectId, Func<string, string>? topicNamingStrategy = null)

    Initializes a new instance of the `GooglePubSubBrokerPublisher` class.

    client: PublisherServiceApiClient
    The Google Cloud Pub/Sub publisher service API client.
    projectId: string
    The Google Cloud project identifier containing the target topics.
    topicNamingStrategy: Func<string, string>?
    An optional function that derives the topic name from the message type alias. If `null`, a default strategy is used.

    Exceptions: ArgumentNullException: `client` is `null`; ArgumentException: `projectId` is `null`, empty, or consists only of white-space characters

  • methodPublishAsync<T>
    public async ValueTask<DispatchResult> PublishAsync<T>(MessageEnvelope<T> message, DispatchContext context) where T : notnull

    Inherits documentation from base type or interface.

    message: MessageEnvelope<T>
    context: DispatchContext
  • methodPublishBatchAsync<T>
    public ValueTask<IReadOnlyList<DispatchResult>> PublishBatchAsync<T>(IReadOnlyList<MessageEnvelope<T>> messages, DispatchContext context) where T : notnull

    Inherits documentation from base type or interface.

    messages: IReadOnlyList<MessageEnvelope<T>>
    context: DispatchContext
  • methodPublishRawAsync
    public async ValueTask<DispatchResult> PublishRawAsync(OutboxMessage message, OutboxMessageMetadata metadata, DispatchContext context)

    Publishes a raw serialized outbox message as-is.

    message: OutboxMessage
    The raw outbox message to publish.
    metadata: OutboxMessageMetadata
    The metadata associated with the message.
    context: DispatchContext
    The context governing the dispatch operation, including cancellation tokens.

    Retorna: A task that represents the asynchronous dispatch operation, containing the `DispatchResult`.

    Used by the Dispatcher which works with pre-serialized payloads, avoiding runtime generics and reflection for NativeAOT compatibility. DispatchResult contract for implementers: **Scenario**: **Return value**: - **Message published successfully**: **`DispatchResult.Ok()`**: - **Transient / recoverable failure (network timeout, broker unreachable, rate-limited)**: **`DispatchResult.FailAndRetry(exception)`**: - **Fatal / unrecoverable failure (schema mismatch, serialization error, message too large for broker, authorization denied)**: **`DispatchResult.FailFatal(exception)`**: Do NOT throw exceptions here. Thrown exceptions are treated as fatal failures by the dispatcher (equivalent to `DispatchResult.FailFatal`). Always catch broker exceptions and map them to the appropriate `DispatchResult`. Do NOT return `default(DispatchResult)`. The default value of the struct (`Success=false, ShouldRetry=false, Error=null`) is an invalid state that will cause the dispatcher to dead-letter the message with a misleading "no error" state. Always use one of the factory methods: `DispatchResult.Ok()`, `DispatchResult.FailAndRetry(ex)`, or `DispatchResult.FailFatal(ex)`. The dispatcher wraps calls to the publisher with a retry interceptor, which automatically retries `FailAndRetry` results with exponential backoff. Returning `FailFatal` bypasses retry and dead-letters the message immediately. OpenTelemetry — `messaging.system` tag requirement: The outbox core sets `messaging.system = "outbox"` as a default on the dispatch Activity. Broker implementers MUST override this tag with the actual broker name: `System.Diagnostics.Activity.Current?.SetTag("messaging.system", "rabbitmq"); // or "kafka", "azure_service_bus", etc.` This is required by the OpenTelemetry Messaging Semantic Conventions (v1.26+): https://opentelemetry.io/docs/specs/semconv/messaging/messaging-spans/#messaging-attributes

EricksonLopez.Outbox.Brokers.Kafka#

1
class

KafkaBrokerPublisher

Ensamblado: EricksonLopez.Outbox.Brokers.Kafka
public sealed class KafkaBrokerPublisher : IBrokerPublisher
Implementa: IBrokerPublisher

Provides a broker publisher implementation that dispatches outbox messages to an Apache Kafka cluster.

Miembros (4)

  • constructorKafkaBrokerPublisher
    public KafkaBrokerPublisher(IProducer<byte[], byte[]> producer, IOutboxSerializer serializer, string defaultTopic)

    Initializes a new instance of the `KafkaBrokerPublisher` class.

    producer: IProducer<byte[], byte[]>
    The Kafka producer instance that sends messages.
    serializer: IOutboxSerializer
    The serializer that encodes the message payload.
    defaultTopic: string
    The default Kafka topic to which messages are published if not overridden by metadata.

    Exceptions: ArgumentNullException: `producer` or `serializer` is `null`

  • methodPublishAsync<T>
    public async ValueTask<DispatchResult> PublishAsync<T>(MessageEnvelope<T> message, DispatchContext context) where T : notnull

    Inherits documentation from base type or interface.

    message: MessageEnvelope<T>
    context: DispatchContext
  • methodPublishBatchAsync<T>
    public async ValueTask<IReadOnlyList<DispatchResult>> PublishBatchAsync<T>(IReadOnlyList<MessageEnvelope<T>> messages, DispatchContext context) where T : notnull

    Inherits documentation from base type or interface.

    messages: IReadOnlyList<MessageEnvelope<T>>
    context: DispatchContext
  • methodPublishRawAsync
    public async ValueTask<DispatchResult> PublishRawAsync(OutboxMessage message, EricksonLopez.Outbox.OutboxMessageMetadata metadata, DispatchContext context)

    Publishes a raw serialized outbox message as-is.

    message: OutboxMessage
    The raw outbox message to publish.
    metadata: EricksonLopez.Outbox.OutboxMessageMetadata
    The metadata associated with the message.
    context: DispatchContext
    The context governing the dispatch operation, including cancellation tokens.

    Retorna: A task that represents the asynchronous dispatch operation, containing the `DispatchResult`.

    Used by the Dispatcher which works with pre-serialized payloads, avoiding runtime generics and reflection for NativeAOT compatibility. DispatchResult contract for implementers: **Scenario**: **Return value**: - **Message published successfully**: **`DispatchResult.Ok()`**: - **Transient / recoverable failure (network timeout, broker unreachable, rate-limited)**: **`DispatchResult.FailAndRetry(exception)`**: - **Fatal / unrecoverable failure (schema mismatch, serialization error, message too large for broker, authorization denied)**: **`DispatchResult.FailFatal(exception)`**: Do NOT throw exceptions here. Thrown exceptions are treated as fatal failures by the dispatcher (equivalent to `DispatchResult.FailFatal`). Always catch broker exceptions and map them to the appropriate `DispatchResult`. Do NOT return `default(DispatchResult)`. The default value of the struct (`Success=false, ShouldRetry=false, Error=null`) is an invalid state that will cause the dispatcher to dead-letter the message with a misleading "no error" state. Always use one of the factory methods: `DispatchResult.Ok()`, `DispatchResult.FailAndRetry(ex)`, or `DispatchResult.FailFatal(ex)`. The dispatcher wraps calls to the publisher with a retry interceptor, which automatically retries `FailAndRetry` results with exponential backoff. Returning `FailFatal` bypasses retry and dead-letters the message immediately. OpenTelemetry — `messaging.system` tag requirement: The outbox core sets `messaging.system = "outbox"` as a default on the dispatch Activity. Broker implementers MUST override this tag with the actual broker name: `System.Diagnostics.Activity.Current?.SetTag("messaging.system", "rabbitmq"); // or "kafka", "azure_service_bus", etc.` This is required by the OpenTelemetry Messaging Semantic Conventions (v1.26+): https://opentelemetry.io/docs/specs/semconv/messaging/messaging-spans/#messaging-attributes

EricksonLopez.Outbox.Brokers.Nats#

1
class

NatsBrokerPublisher

Ensamblado: EricksonLopez.Outbox.Brokers.Nats
public sealed class NatsBrokerPublisher : IBrokerPublisher
Implementa: IBrokerPublisher

Provides a broker publisher implementation that dispatches outbox messages to NATS using the official NATS.Net v2 client.

Notas:

Design decisions: - Uses NATS subject-per-message-type routing (e.g. "order.created.v1"). - Leverages NATS headers to propagate correlation and causation IDs. - PublishRawAsync sends the raw payload bytes directly — avoids a double-serialization round-trip.

Miembros (4)

  • constructorNatsBrokerPublisher
    public NatsBrokerPublisher(INatsConnection connection)

    Initializes a new instance of the `NatsBrokerPublisher` class.

    connection: INatsConnection
    The NATS connection client.

    Exceptions: ArgumentNullException: `connection` is `null`

  • methodPublishAsync<T>
    public async ValueTask<DispatchResult> PublishAsync<T>(MessageEnvelope<T> message, DispatchContext context) where T : notnull

    Inherits documentation from base type or interface.

    message: MessageEnvelope<T>
    context: DispatchContext
  • methodPublishBatchAsync<T>
    public async ValueTask<IReadOnlyList<DispatchResult>> PublishBatchAsync<T>(IReadOnlyList<MessageEnvelope<T>> messages, DispatchContext context) where T : notnull

    Inherits documentation from base type or interface.

    messages: IReadOnlyList<MessageEnvelope<T>>
    context: DispatchContext
  • methodPublishRawAsync
    public async ValueTask<DispatchResult> PublishRawAsync(OutboxMessage message, OutboxMessageMetadata metadata, DispatchContext context)

    Publishes a raw serialized outbox message as-is.

    message: OutboxMessage
    The raw outbox message to publish.
    metadata: OutboxMessageMetadata
    The metadata associated with the message.
    context: DispatchContext
    The context governing the dispatch operation, including cancellation tokens.

    Retorna: A task that represents the asynchronous dispatch operation, containing the `DispatchResult`.

    Used by the Dispatcher which works with pre-serialized payloads, avoiding runtime generics and reflection for NativeAOT compatibility. DispatchResult contract for implementers: **Scenario**: **Return value**: - **Message published successfully**: **`DispatchResult.Ok()`**: - **Transient / recoverable failure (network timeout, broker unreachable, rate-limited)**: **`DispatchResult.FailAndRetry(exception)`**: - **Fatal / unrecoverable failure (schema mismatch, serialization error, message too large for broker, authorization denied)**: **`DispatchResult.FailFatal(exception)`**: Do NOT throw exceptions here. Thrown exceptions are treated as fatal failures by the dispatcher (equivalent to `DispatchResult.FailFatal`). Always catch broker exceptions and map them to the appropriate `DispatchResult`. Do NOT return `default(DispatchResult)`. The default value of the struct (`Success=false, ShouldRetry=false, Error=null`) is an invalid state that will cause the dispatcher to dead-letter the message with a misleading "no error" state. Always use one of the factory methods: `DispatchResult.Ok()`, `DispatchResult.FailAndRetry(ex)`, or `DispatchResult.FailFatal(ex)`. The dispatcher wraps calls to the publisher with a retry interceptor, which automatically retries `FailAndRetry` results with exponential backoff. Returning `FailFatal` bypasses retry and dead-letters the message immediately. OpenTelemetry — `messaging.system` tag requirement: The outbox core sets `messaging.system = "outbox"` as a default on the dispatch Activity. Broker implementers MUST override this tag with the actual broker name: `System.Diagnostics.Activity.Current?.SetTag("messaging.system", "rabbitmq"); // or "kafka", "azure_service_bus", etc.` This is required by the OpenTelemetry Messaging Semantic Conventions (v1.26+): https://opentelemetry.io/docs/specs/semconv/messaging/messaging-spans/#messaging-attributes

EricksonLopez.Outbox.Brokers.RedisStreams#

1
class

RedisStreamsBrokerPublisher

Ensamblado: EricksonLopez.Outbox.Brokers.RedisStreams
public sealed class RedisStreamsBrokerPublisher : IBrokerPublisher
Implementa: IBrokerPublisher

Provides a broker publisher implementation that dispatches outbox messages to Redis Streams using StackExchange.Redis.

Notas:

Design decisions: - Stream key is derived from the message type (e.g. "outbox:order.created.v1"). - Uses XADD with MAXLEN ~ to cap stream length and prevent unbounded growth (auto-trim). - Payload stored as "payload" field; metadata headers stored individually. - Redis Streams deliver at-least-once; consumers must implement idempotency via the Inbox pattern. Trade-off vs Kafka: + No broker to deploy separately if Redis already exists. + Consumer groups provide pub/sub fan-out with persistence. - Not designed for high-throughput analytics workloads.

Miembros (4)

  • constructorRedisStreamsBrokerPublisher
    public RedisStreamsBrokerPublisher(IConnectionMultiplexer redis, int maxStreamLength = 10_000)

    Initializes a new instance of the `RedisStreamsBrokerPublisher` class.

    redis: IConnectionMultiplexer
    The Redis connection multiplexer.
    maxStreamLength: int
    The maximum length of the Redis stream. Defaults to 10,000.

    Exceptions: ArgumentNullException: `redis` is `null`

  • methodPublishAsync<T>
    public async ValueTask<DispatchResult> PublishAsync<T>(MessageEnvelope<T> message, DispatchContext context) where T : notnull

    Inherits documentation from base type or interface.

    message: MessageEnvelope<T>
    context: DispatchContext
  • methodPublishBatchAsync<T>
    public async ValueTask<IReadOnlyList<DispatchResult>> PublishBatchAsync<T>(IReadOnlyList<MessageEnvelope<T>> messages, DispatchContext context) where T : notnull

    Inherits documentation from base type or interface.

    messages: IReadOnlyList<MessageEnvelope<T>>
    context: DispatchContext
  • methodPublishRawAsync
    public async ValueTask<DispatchResult> PublishRawAsync(OutboxMessage message, OutboxMessageMetadata metadata, DispatchContext context)

    Publishes a raw serialized outbox message as-is.

    message: OutboxMessage
    The raw outbox message to publish.
    metadata: OutboxMessageMetadata
    The metadata associated with the message.
    context: DispatchContext
    The context governing the dispatch operation, including cancellation tokens.

    Retorna: A task that represents the asynchronous dispatch operation, containing the `DispatchResult`.

    Used by the Dispatcher which works with pre-serialized payloads, avoiding runtime generics and reflection for NativeAOT compatibility. DispatchResult contract for implementers: **Scenario**: **Return value**: - **Message published successfully**: **`DispatchResult.Ok()`**: - **Transient / recoverable failure (network timeout, broker unreachable, rate-limited)**: **`DispatchResult.FailAndRetry(exception)`**: - **Fatal / unrecoverable failure (schema mismatch, serialization error, message too large for broker, authorization denied)**: **`DispatchResult.FailFatal(exception)`**: Do NOT throw exceptions here. Thrown exceptions are treated as fatal failures by the dispatcher (equivalent to `DispatchResult.FailFatal`). Always catch broker exceptions and map them to the appropriate `DispatchResult`. Do NOT return `default(DispatchResult)`. The default value of the struct (`Success=false, ShouldRetry=false, Error=null`) is an invalid state that will cause the dispatcher to dead-letter the message with a misleading "no error" state. Always use one of the factory methods: `DispatchResult.Ok()`, `DispatchResult.FailAndRetry(ex)`, or `DispatchResult.FailFatal(ex)`. The dispatcher wraps calls to the publisher with a retry interceptor, which automatically retries `FailAndRetry` results with exponential backoff. Returning `FailFatal` bypasses retry and dead-letters the message immediately. OpenTelemetry — `messaging.system` tag requirement: The outbox core sets `messaging.system = "outbox"` as a default on the dispatch Activity. Broker implementers MUST override this tag with the actual broker name: `System.Diagnostics.Activity.Current?.SetTag("messaging.system", "rabbitmq"); // or "kafka", "azure_service_bus", etc.` This is required by the OpenTelemetry Messaging Semantic Conventions (v1.26+): https://opentelemetry.io/docs/specs/semconv/messaging/messaging-spans/#messaging-attributes

EricksonLopez.Outbox.Contracts#

3
class

IdempotentConsumerAttribute

Ensamblado: EricksonLopez.Outbox.Abstractions
public sealed class IdempotentConsumerAttribute : Attribute
Hereda de: Attribute

Marks a consumer class as intentionally idempotent, suppressing the OUTBOX003 analyzer warning.

Miembros (0)

Este tipo declara 0 miembros públicos (por ejemplo, interfaz marcadora o enum/record vacío).

class

InboxConsumerAttribute

Ensamblado: EricksonLopez.Outbox.Abstractions
public sealed class InboxConsumerAttribute : Attribute
Hereda de: Attribute

Marks a method as an Inbox consumer (Handler) for a specific event type.

Miembros (4)

  • constructorInboxConsumerAttribute
    public InboxConsumerAttribute(string eventAlias)

    Initializes a new instance of the `InboxConsumerAttribute` class.

    eventAlias: string
    The stable string alias identifying the event type this consumer handles.

    Exceptions: ArgumentException: `eventAlias` is `null` or white space

  • constructorInboxConsumerAttribute
    public InboxConsumerAttribute(string eventAlias, int maxAgeMinutes)

    Initializes a new instance of the `InboxConsumerAttribute` class with a specific idempotency retention max age.

    eventAlias: string
    The stable string alias identifying the event type this consumer handles.
    maxAgeMinutes: int
    The maximum retention duration in minutes for deduplication records.

    Exceptions: ArgumentException: `eventAlias` is `null` or white space

  • propertyEventAlias
    public string EventAlias { get; }

    Gets the event alias that this consumer subscribes to.

  • propertyMaxAgeMinutes
    public int MaxAgeMinutes { get; set; }

    Gets or sets the optional expiration time in minutes for idempotency records tracked by this consumer. A value of `0` or negative indicates the default retention period applies.

class

OutboxMessageAttribute

Ensamblado: EricksonLopez.Outbox.Abstractions
public sealed class OutboxMessageAttribute : Attribute
Hereda de: Attribute

Marks a class or record as a valid message or event for the outbox processing pipeline.

Miembros (2)

  • constructorOutboxMessageAttribute
    public OutboxMessageAttribute(string alias)

    Initializes a new instance of the `OutboxMessageAttribute` class.

    alias: string
    The stable string alias identifying the message type.

    Exceptions: ArgumentException: `alias` is `null` or white space

  • propertyAlias
    public string Alias { get; }

    Gets the unique alias (Type Mapping) that will be stored in the database.

EricksonLopez.Outbox.Dapr#

2
class

DaprBrokerPublisher

Ensamblado: EricksonLopez.Outbox.Dapr
public sealed class DaprBrokerPublisher : IBrokerPublisher
Implementa: IBrokerPublisher

Provides a broker publisher implementation that dispatches outbox messages using the Dapr Pub/Sub component API.

Miembros (3)

  • constructorDaprBrokerPublisher
    public DaprBrokerPublisher(DaprClient daprClient, string pubsubName = "")

    Initializes a new instance of the `DaprBrokerPublisher` class.

    daprClient: DaprClient
    The Dapr client instance.
    pubsubName: string
    The name of the configured Dapr Pub/Sub component (default: "pubsub").

    Exceptions: ArgumentNullException: `daprClient` is `null`

  • methodPublishRawAsync
    public async ValueTask<DispatchResult> PublishRawAsync(OutboxMessage message, OutboxMessageMetadata metadata, DispatchContext context)

    Publishes a raw serialized outbox message as-is.

    message: OutboxMessage
    The raw outbox message to publish.
    metadata: OutboxMessageMetadata
    The metadata associated with the message.
    context: DispatchContext
    The context governing the dispatch operation, including cancellation tokens.

    Retorna: A task that represents the asynchronous dispatch operation, containing the `DispatchResult`.

    Used by the Dispatcher which works with pre-serialized payloads, avoiding runtime generics and reflection for NativeAOT compatibility. DispatchResult contract for implementers: **Scenario**: **Return value**: - **Message published successfully**: **`DispatchResult.Ok()`**: - **Transient / recoverable failure (network timeout, broker unreachable, rate-limited)**: **`DispatchResult.FailAndRetry(exception)`**: - **Fatal / unrecoverable failure (schema mismatch, serialization error, message too large for broker, authorization denied)**: **`DispatchResult.FailFatal(exception)`**: Do NOT throw exceptions here. Thrown exceptions are treated as fatal failures by the dispatcher (equivalent to `DispatchResult.FailFatal`). Always catch broker exceptions and map them to the appropriate `DispatchResult`. Do NOT return `default(DispatchResult)`. The default value of the struct (`Success=false, ShouldRetry=false, Error=null`) is an invalid state that will cause the dispatcher to dead-letter the message with a misleading "no error" state. Always use one of the factory methods: `DispatchResult.Ok()`, `DispatchResult.FailAndRetry(ex)`, or `DispatchResult.FailFatal(ex)`. The dispatcher wraps calls to the publisher with a retry interceptor, which automatically retries `FailAndRetry` results with exponential backoff. Returning `FailFatal` bypasses retry and dead-letters the message immediately. OpenTelemetry — `messaging.system` tag requirement: The outbox core sets `messaging.system = "outbox"` as a default on the dispatch Activity. Broker implementers MUST override this tag with the actual broker name: `System.Diagnostics.Activity.Current?.SetTag("messaging.system", "rabbitmq"); // or "kafka", "azure_service_bus", etc.` This is required by the OpenTelemetry Messaging Semantic Conventions (v1.26+): https://opentelemetry.io/docs/specs/semconv/messaging/messaging-spans/#messaging-attributes

  • propertyBrokerSystemName
    public string BrokerSystemName { get; }

    Gets the OpenTelemetry `messaging.system` attribute value for this broker implementation.

    The outbox dispatcher reads this value to set the `messaging.system` tag on the dispatch `Diagnostics.Activity`, conforming to the OpenTelemetry Messaging Semantic Conventions (v1.26+). See: https://opentelemetry.io/docs/specs/semconv/messaging/messaging-spans/ Override this property in your broker publisher to return the canonical OTel system name: **Broker**: **Return value**: - **RabbitMQ**: **`"rabbitmq"`**: - **Apache Kafka**: **`"kafka"`**: - **Azure Service Bus**: **`"azure_service_bus"`**: - **Amazon SQS**: **`"aws_sqs"`**: - **Google Pub/Sub**: **`"gcp_pubsub"`**: - **NATS**: **`"nats"`**: - **Redis Streams**: **`"redis"`**: The default implementation returns `"outbox"` as a fallback sentinel value. The dispatcher will use this value automatically — broker publishers no longer need to call `Activity.Current?.SetTag("messaging.system", ...)` manually.

class

DaprOutboxExtensions

Ensamblado: EricksonLopez.Outbox.Dapr
public static class DaprOutboxExtensions

Provides extension methods for configuring Dapr Pub/Sub broker integration.

Miembros (2)

  • methodAddDaprBrokerPublisher
    public static IServiceCollection AddDaprBrokerPublisher(this IServiceCollection services, string pubsubName = "")

    Registers the `DaprBrokerPublisher` as a broker publisher in the service collection.

    services: this IServiceCollection
    The service collection.
    pubsubName: string
    The name of the Dapr pub/sub component.

    Retorna: The service collection.

    Exceptions: ArgumentNullException: `services` is `null`

  • methodUseDapr
    public static OutboxOptions UseDapr(this OutboxOptions options, string pubsubName = "")

    Configures the outbox to use Dapr Pub/Sub as the default message broker.

    options: this OutboxOptions
    The outbox options.
    pubsubName: string
    The name of the Dapr pub/sub component.

    Retorna: The outbox options for method chaining.

    Exceptions: ArgumentNullException: `options` is `null`

EricksonLopez.Outbox.Diagnostics#

6
class

DefaultErrorSanitizer

Ensamblado: EricksonLopez.Outbox
public sealed partial class DefaultErrorSanitizer : IErrorSanitizer
Implementa: IErrorSanitizer

Provides the default implementation of `IErrorSanitizer` that strips known sensitive patterns (passwords, connection strings, bearer tokens) from exception messages.

Miembros (2)

  • methodSanitize
    public string Sanitize(Exception exception)

    Sanitizes the given exception into a safe string representation.

    exception: Exception
    The exception to sanitize.

    Retorna: A sanitized string representation of the error.

  • methodSanitize
    public string Sanitize(string text)

    Sanitizes the given exception into a safe string representation.

    text: string

    Retorna: A sanitized string representation of the error.

interface

IErrorSanitizer

Ensamblado: EricksonLopez.Outbox
public interface IErrorSanitizer

Provides a mechanism to sanitize exceptions before they are logged or stored in the database. Useful for masking sensitive information (e.g., PII, passwords, connection strings) that might leak in raw exception messages.

Miembros (2)

  • methodSanitize
    string Sanitize(Exception exception)

    Sanitizes the given exception into a safe string representation.

    exception: Exception
    The exception to sanitize.

    Retorna: A sanitized string representation of the error.

  • methodSanitize
    string Sanitize(string text)

    Sanitizes sensitive patterns from raw text or JSON payloads.

    text: string
class

OutboxActivitySource

Ensamblado: EricksonLopez.Outbox
public static class OutboxActivitySource

Provides strongly-typed OpenTelemetry tracing capabilities for the Outbox pattern, propagating W3C TraceContext across the transaction-boundary gap between message storage and broker dispatch.

Notas:

Links producer spans across time boundaries (database write → dispatcher publish) to guarantee end-to-end observability in distributed systems. Follows the OpenTelemetry Messaging Semantic Conventions: https://opentelemetry.io/docs/specs/semconv/messaging/

Miembros (5)

  • methodStartDispatchActivity
    public static Activity? StartDispatchActivity(string messageType, string? correlationId, string? parentTraceId, string? parentTraceState = null, string? messageId = null, string? brokerSystemName = null)

    Starts a tracing activity when a message is dispatched to the network. This should link back to the TraceId originally saved in the database metadata. Emitted tags follow the OpenTelemetry Messaging Semantic Conventions (v1.26+): - `messaging.system` — identifies the messaging broker. Defaults to `"outbox"` when no broker-specific name is provided. The dispatcher automatically reads `IBrokerPublisher.BrokerSystemName` from the registered broker publisher and passes it here, so this tag is populated with the actual broker name (e.g., `"rabbitmq"`, `"kafka"`) when the broker publisher overrides the property. - `messaging.operation.name` — always "publish" for the producer side. - `messaging.operation.type` — always "publish" for the producer side (OTel semconv 2024 structured enum, parallel to `messaging.operation.name`). - `messaging.destination.name` — the message type alias (routing key). - `messaging.message.id` — the unique outbox message ID. - `messaging.message.conversation_id` — the correlation ID for tracing across services.

    messageType: string
    Message type alias used as the destination name.
    correlationId: string?
    Optional correlation ID (W3C conversation ID).
    parentTraceId: string?
    Optional W3C traceparent header from message headers.
    parentTraceState: string?
    Optional W3C tracestate header from message headers.
    messageId: string?
    Optional unique outbox message ID.
    brokerSystemName: string?
    The broker-specific `messaging.system` value (e.g., "rabbitmq", "kafka", "aws_sqs"). When `null`, defaults to `"outbox"`. Broker publishers should supply this to comply with OTel Messaging semantic conventions. See `OutboxSystemName`.
  • methodStartStoreActivity
    public static Activity? StartStoreActivity(string messageType, string messageId, string? correlationId = null)

    Starts a tracing activity when a message is first stored in the outbox (producer "create" operation). This activity completes the end-to-end trace chain: - Business transaction → outbox.create (the store operation) - Dispatcher reads message → `StartDispatchActivity` (outbox.publish) OTel Messaging Semantic Convention operation type: `"create"` Provides the producer side when a message is first produced but not yet transmitted. Reference: https://opentelemetry.io/docs/specs/semconv/messaging/messaging-spans/#operation-types The `messaging.system` tag is set to `"outbox"` for store activities because the store operation is logically part of the outbox infrastructure, not the broker. The dispatch activity uses the actual broker name.

    messageType: string
    The message type alias (e.g., "order.created.v1").
    messageId: string
    The Guid of the outbox message, for correlation.
    correlationId: string?
    Optional W3C conversation ID for distributed tracing.

    Retorna: The started activity, or `null` if no listeners are registered.

  • fieldOutboxSystemName
    public const string OutboxSystemName

    Gets the fallback `messaging.system` tag value used when the actual broker name is not known. Store activities always use this value. Dispatch activities should use the actual broker name (`"rabbitmq"`, `"kafka"`, etc.) via the `brokerSystemName` parameter of `StartDispatchActivity`.

  • fieldSource
    public static readonly ActivitySource Source

    Gets the `ActivitySource` instance used by the Outbox.

  • fieldSourceName
    public const string SourceName

    Gets the name of the ActivitySource for distributed tracing.

class

OutboxEventIds

Ensamblado: EricksonLopez.Outbox
public static class OutboxEventIds

Centralized event IDs for all EricksonLopez.Outbox log messages. Range 10000-10099: Dispatcher / channel events Range 10100-10199: Startup / configuration events Range 10200-10299: Poller events Range 10300-10399: Idempotency / inbox events .

Miembros (31)

  • fieldBatchFetched
    public static readonly EventId BatchFetched

    Event ID for BatchFetched.

  • fieldChannelCancelled
    public static readonly EventId ChannelCancelled

    Event ID for ChannelCancelled.

  • fieldCircuitBreakerHalfOpen
    public static readonly EventId CircuitBreakerHalfOpen

    Event ID for CircuitBreakerHalfOpen.

  • fieldCircuitBreakerReset
    public static readonly EventId CircuitBreakerReset

    Event ID for CircuitBreakerReset.

  • fieldCircuitBreakerTripped
    public static readonly EventId CircuitBreakerTripped

    Event ID for CircuitBreakerTripped.

  • fieldDbRetryAttempt
    public static readonly EventId DbRetryAttempt

    Event ID for DbRetryAttempt.

  • fieldDispatcherConsumerCrashed
    public static readonly EventId DispatcherConsumerCrashed

    Event ID for DispatcherConsumerCrashed.

  • fieldDispatcherConsumerStarted
    public static readonly EventId DispatcherConsumerStarted

    Event ID for DispatcherConsumerStarted.

  • fieldDispatcherStarting
    public static readonly EventId DispatcherStarting

    Event ID for DispatcherStarting.

  • fieldDispatcherStopped
    public static readonly EventId DispatcherStopped

    Event ID for DispatcherStopped.

  • fieldDlqInsertFailed
    public static readonly EventId DlqInsertFailed

    Event ID for DlqInsertFailed.

  • fieldDlqPayloadFallback
    public static readonly EventId DlqPayloadFallback

    Event ID for DlqPayloadFallback. Emitted when a DLQ INSERT fails and the message payload is written to the structured log as a fallback recovery record. Allows log aggregators (Seq, Loki, etc.) to act as a DLQ fallback.

  • fieldHeadersDeserializeFailed
    public static readonly EventId HeadersDeserializeFailed

    Event ID for HeadersDeserializeFailed.

  • fieldHeadersTooLarge
    public static readonly EventId HeadersTooLarge

    Event ID for HeadersTooLarge.

  • fieldInboxCleanupError
    public static readonly EventId InboxCleanupError

    Event ID for InboxCleanupError.

  • fieldInboxCleanupPurged
    public static readonly EventId InboxCleanupPurged

    Event ID for InboxCleanupPurged.

  • fieldInboxCleanupStarted
    public static readonly EventId InboxCleanupStarted

    Event ID for InboxCleanupStarted.

  • fieldInboxDuplicateDetected
    public static readonly EventId InboxDuplicateDetected

    Event ID for InboxDuplicateDetected.

  • fieldInvalidDispatchResultDetected
    public static readonly EventId InvalidDispatchResultDetected

    Event ID for InvalidDispatchResultDetected.

  • fieldMessageDeadLettered
    public static readonly EventId MessageDeadLettered

    Event ID for MessageDeadLettered.

  • fieldMessageDelayedNoRetry
    public static readonly EventId MessageDelayedNoRetry

    Event ID for MessageDelayedNoRetry.

  • fieldMessageDispatchFailed
    public static readonly EventId MessageDispatchFailed

    Event ID for MessageDispatchFailed.

  • fieldMessageDispatched
    public static readonly EventId MessageDispatched

    Event ID for MessageDispatched.

  • fieldMessageRetried
    public static readonly EventId MessageRetried

    Event ID for MessageRetried.

  • fieldPayloadTooLarge
    public static readonly EventId PayloadTooLarge

    Event ID for PayloadTooLarge.

  • fieldPollerError
    public static readonly EventId PollerError

    Event ID for PollerError.

  • fieldPollerStarted
    public static readonly EventId PollerStarted

    Event ID for PollerStarted.

  • fieldPollerStopped
    public static readonly EventId PollerStopped

    Event ID for PollerStopped.

  • fieldProducerOnlyMode
    public static readonly EventId ProducerOnlyMode

    Event ID for ProducerOnlyMode.

  • fieldStartupValidationFailed
    public static readonly EventId StartupValidationFailed

    Event ID for StartupValidationFailed.

  • fieldStartupValidationPassed
    public static readonly EventId StartupValidationPassed

    Event ID for StartupValidationPassed.

class

OutboxLogMessages

Ensamblado: EricksonLopez.Outbox
public static partial class OutboxLogMessages

Provides source-generated log messages (via `[LoggerMessage]` attribute) for all hot-path log calls. Why: The previous implementation used direct _logger.LogXxx() calls everywhere, which allocate a params object[] for each call site on every invocation, even if logging is disabled. [LoggerMessage] generates static delegates at compile time that short-circuit on disabled log levels with zero allocation. All hot-path messages (dispatched, failed, dead-lettered, retried) must use this pattern. Note for contributors (G13.1): Declared `static partial` because the C# compiler requires `partial` for source-generated `[LoggerMessage]` methods. The compiler generates a companion file (`OutboxLogMessages.g.cs`) in `obj/`. There is no manually-authored counterpart file — this file is the single source of truth for all log message definitions. Do not create another `partial class OutboxLogMessages` file.

Miembros (31)

  • methodBatchFetched
    public static partial void BatchFetched(this ILogger logger, int count, long elapsedMs)

    Logs the retrieval of a batch of pending messages from the outbox database table.

    logger: this ILogger
    The logger instance to write the event to.
    count: int
    The number of messages fetched in the batch.
    elapsedMs: long
    The elapsed duration of the database fetch in milliseconds.
  • methodChannelCancelled
    public static partial void ChannelCancelled(this ILogger logger)

    Logs when message processing across the outbox channel is cancelled during graceful shutdown.

    logger: this ILogger
    The logger instance to write the event to.
  • methodDbRetryAttempt
    public static partial void DbRetryAttempt(this ILogger logger, Exception exception, int attempt, int maxAttempts)

    Logs a transient database error retry attempt during an outbox persistence operation.

    logger: this ILogger
    The logger instance to write the event to.
    exception: Exception
    The transient database exception that triggered the retry.
    attempt: int
    The current retry attempt number.
    maxAttempts: int
    The maximum retry attempts configured for database operations.
  • methodDispatcherConsumerCrashed
    public static partial void DispatcherConsumerCrashed(this ILogger logger, Exception exception, int consumerId)

    Logs when an outbox dispatch consumer worker crashes due to an unhandled exception.

    logger: this ILogger
    The logger instance to write the event to.
    exception: Exception
    The unhandled exception that caused the consumer worker crash.
    consumerId: int
    The zero-based index or identifier of the crashed consumer worker.
  • methodDispatcherConsumerStarted
    public static partial void DispatcherConsumerStarted(this ILogger logger, int consumerId)

    Logs when an outbox dispatch consumer worker starts its processing loop.

    logger: this ILogger
    The logger instance to write the event to.
    consumerId: int
    The zero-based index or identifier of the started consumer worker.
  • methodDispatcherConsumerStopped
    public static partial void DispatcherConsumerStopped(this ILogger logger, int consumerId)

    Logs when an outbox dispatch consumer worker terminates its processing loop.

    logger: this ILogger
    The logger instance to write the event to.
    consumerId: int
    The zero-based index or identifier of the stopped consumer worker.
  • methodDispatcherStarting
    public static partial void DispatcherStarting(this ILogger logger, int maxDOP, int batchSize, bool adaptive)

    Logs the startup of the outbox dispatcher background service with its operational parameters.

    logger: this ILogger
    The logger instance to write the event to.
    maxDOP: int
    The maximum degree of parallelism for concurrent dispatching.
    batchSize: int
    The configured batch size for message retrieval.
    adaptive: bool
    A value indicating whether adaptive polling is enabled.
  • methodDispatcherStopped
    public static partial void DispatcherStopped(this ILogger logger)

    Logs when the outbox dispatcher stops processing during application shutdown.

    logger: this ILogger
    The logger instance to write the event to.
  • methodDlqInsertFailed
    public static partial void DlqInsertFailed(this ILogger logger, Exception exception, Guid messageId, string messageType)

    Logs a failure encountered while inserting a message into the dead-letter queue repository.

    logger: this ILogger
    The logger instance to write the event to.
    exception: Exception
    The exception that occurred during insertion into the dead-letter repository.
    messageId: Guid
    The unique identifier of the message.
    messageType: string
    The message type alias or CLR type name.
  • methodDlqPayloadFallback
    public static partial void DlqPayloadFallback(this ILogger logger, Guid messageId, string messageType, int retryCount, string reason, string payloadJson)

    Logs a DLQ payload fallback record when the DLQ INSERT fails and the message payload fits within the configured safe size limit.

    logger: this ILogger
    The logger instance to write the event to.
    messageId: Guid
    The unique identifier of the message.
    messageType: string
    The message type alias or CLR type name.
    retryCount: int
    The retry count reached before dead-lettering.
    reason: string
    The failure reason explaining why the message was dead-lettered.
    payloadJson: string
    The JSON-serialized payload preserved for operator recovery.

    F-04 AUDIT FIX — DLQ INSERT failure recovery: When `IDeadLetterRepository.InsertAsync` throws, the dead-letter record is lost from the DLQ table. Without this log, operators would only know the message ID (from DlqInsertFailed) but would have no access to the original payload for manual recovery or replay. This log emits the message payload as a structured field so that log aggregators (Seq, Loki, Elasticsearch, Azure Monitor) can be queried for all `DlqPayloadFallback` events and the payloads can be replayed without requiring access to the database. Security note: The payload is written to logs as-is (truncated to `MaxPayloadSizeInBytes` to prevent log flooding). If payloads contain PII or secrets, ensure your log aggregator applies appropriate access controls and retention policies to this event stream. This log is suppressed when the payload exceeds `OutboxRuntimeOptions.MaxPayloadSizeInBytes` to prevent single large messages from flooding the log infrastructure.

  • methodHeadersDeserializeFailed
    public static partial void HeadersDeserializeFailed(this ILogger logger, Exception exception, Guid messageId)

    Logs a failure encountered when deserializing message headers from binary or JSON format.

    logger: this ILogger
    The logger instance to write the event to.
    exception: Exception
    The exception that occurred during header deserialization.
    messageId: Guid
    The unique identifier of the message.
  • methodHeadersTooLarge
    public static partial void HeadersTooLarge(this ILogger logger, Guid messageId, int length)

    Logs when serialized outbox message headers exceed the configured maximum allowed size.

    logger: this ILogger
    The logger instance to write the event to.
    messageId: Guid
    The unique identifier of the message.
    length: int
    The serialized headers size in bytes.
  • methodInboxCleanupError
    public static partial void InboxCleanupError(this ILogger logger, Exception exception)

    Logs an error encountered during the inbox cleanup execution cycle.

    logger: this ILogger
    The logger instance to write the event to.
    exception: Exception
    The exception that occurred during inbox cleanup.
  • methodInboxCleanupPurged
    public static partial void InboxCleanupPurged(this ILogger logger, DateTimeOffset cutoff)

    Logs the successful purge of expired idempotency records from the inbox store.

    logger: this ILogger
    The logger instance to write the event to.
    cutoff: DateTimeOffset
    The threshold timestamp before which all records were purged.
  • methodInboxCleanupStarted
    public static partial void InboxCleanupStarted(this ILogger logger, TimeSpan retentionPeriod, TimeSpan cleanupInterval)

    Logs the startup of the inbox cleanup background service.

    logger: this ILogger
    The logger instance to write the event to.
    retentionPeriod: TimeSpan
    The retention time span after which processed idempotency records are purged.
    cleanupInterval: TimeSpan
    The interval frequency at which cleanup purge executions run.
  • methodInboxDuplicateDetected
    public static partial void InboxDuplicateDetected(this ILogger logger, Guid messageId, string consumerId)

    Logs when a duplicate incoming message is detected and skipped by the inbox idempotency checker.

    logger: this ILogger
    The logger instance to write the event to.
    messageId: Guid
    The unique identifier of the duplicate message.
    consumerId: string
    The identifier of the consumer processing the message.
  • methodInvalidDispatchResultDetected
    public static partial void InvalidDispatchResultDetected(this ILogger logger, Guid messageId, string messageType)

    Logs a warning when a broker publisher returns an uninitialized default dispatch result.

    logger: this ILogger
    The logger instance to write the event to.
    messageId: Guid
    The unique identifier of the message.
    messageType: string
    The message type alias or CLR type name.
  • methodMessageDeadLettered
    public static partial void MessageDeadLettered(this ILogger logger, Guid messageId, string messageType, int retryCount)

    Logs when an outbox message exhausts all retry attempts and is moved to the dead-letter queue.

    logger: this ILogger
    The logger instance to write the event to.
    messageId: Guid
    The unique identifier of the dead-lettered message.
    messageType: string
    The message type alias or CLR type name.
    retryCount: int
    The total number of retry attempts made before dead-lettering.
  • methodMessageDelayedNoRetry
    public static partial void MessageDelayedNoRetry(this ILogger logger, Guid messageId)

    Logs when a message is delayed without incrementing its retry count due to an open circuit breaker.

    logger: this ILogger
    The logger instance to write the event to.
    messageId: Guid
    The unique identifier of the delayed message.
  • methodMessageDispatchFailed
    public static partial void MessageDispatchFailed(this ILogger logger, Exception exception, Guid messageId, string messageType)

    Logs a failure encountered while dispatching an outbox message to the message broker.

    logger: this ILogger
    The logger instance to write the event to.
    exception: Exception
    The exception that caused the dispatch failure.
    messageId: Guid
    The unique identifier of the message that failed to dispatch.
    messageType: string
    The message type alias or CLR type name.
  • methodMessageDispatched
    public static partial void MessageDispatched(this ILogger logger, Guid messageId, string messageType, long elapsedMs)

    Logs the successful dispatch of an outbox message to the message broker.

    logger: this ILogger
    The logger instance to write the event to.
    messageId: Guid
    The unique identifier of the dispatched message.
    messageType: string
    The message type alias or CLR type name.
    elapsedMs: long
    The elapsed duration of the dispatch operation in milliseconds.
  • methodMessageRetried
    public static partial void MessageRetried(this ILogger logger, Guid messageId, string messageType, int attempt, int maxRetries)

    Logs when an outbox message dispatch fails transiently and is scheduled for a retry attempt.

    logger: this ILogger
    The logger instance to write the event to.
    messageId: Guid
    The unique identifier of the message to retry.
    messageType: string
    The message type alias or CLR type name.
    attempt: int
    The current retry attempt number.
    maxRetries: int
    The maximum allowed retry attempts before dead-lettering.
  • methodPayloadTooLarge
    public static partial void PayloadTooLarge(this ILogger logger, Guid messageId, int length)

    Logs when an outbox message payload exceeds the configured maximum allowed size.

    logger: this ILogger
    The logger instance to write the event to.
    messageId: Guid
    The unique identifier of the message.
    length: int
    The payload size in bytes.
  • methodPollerError
    public static partial void PollerError(this ILogger logger, Exception exception)

    Logs an unhandled error encountered in the outbox poller polling loop.

    logger: this ILogger
    The logger instance to write the event to.
    exception: Exception
    The unhandled exception thrown in the poller loop.
  • methodPollerStarted
    public static partial void PollerStarted(this ILogger logger, int batchSize, double interval, int maxDop)

    Logs when the outbox background poller starts polling the database for pending messages.

    logger: this ILogger
    The logger instance to write the event to.
    batchSize: int
    The maximum number of messages retrieved per batch.
    interval: double
    The polling interval duration in milliseconds.
    maxDop: int
    The maximum degree of parallelism configured for consumer workers.
  • methodPollerStopped
    public static partial void PollerStopped(this ILogger logger)

    Logs when the outbox background poller stops execution during graceful shutdown.

    logger: this ILogger
    The logger instance to write the event to.
  • methodProducerOnlyMode
    public static partial void ProducerOnlyMode(this ILogger logger)

    Logs when the application is configured in producer-only mode with background dispatching disabled.

    logger: this ILogger
    The logger instance to write the event to.
  • methodReclaimedStaleMessages
    public static partial void ReclaimedStaleMessages(this ILogger logger, int count)

    Logs when stale in-flight messages are reclaimed back to the pending state for redelivery.

    logger: this ILogger
    The logger instance to write the event to.
    count: int
    The number of stale messages reset to pending status.
  • methodStartupValidationFailed
    public static partial void StartupValidationFailed(this ILogger logger, int errorCount, string errors)

    Logs when outbox startup validation encounters critical configuration or registration errors.

    logger: this ILogger
    The logger instance to write the event to.
    errorCount: int
    The total number of validation errors detected.
    errors: string
    A concatenated description of all validation error messages.
  • methodStartupValidationPassed
    public static partial void StartupValidationPassed(this ILogger logger)

    Logs when outbox startup validation completes successfully with all dependencies verified.

    logger: this ILogger
    The logger instance to write the event to.
  • methodThirdPartyDeadLetterRepositoryRegistered
    public static partial void ThirdPartyDeadLetterRepositoryRegistered(this ILogger logger, string repositoryType)

    Logs a warning when a custom third-party dead-letter repository is registered in dependency injection.

    logger: this ILogger
    The logger instance to write the event to.
    repositoryType: string
    The CLR type name of the registered dead-letter repository.

    AUDIT-FIX: Renumbered from 10103 to 10112 to resolve EventId collision. EventId 10103 was previously assigned to both DispatcherStarting and ThirdPartyDeadLetterRepositoryRegistered, causing log aggregators to incorrectly merge the two unrelated event streams.

class

OutboxMetrics

Ensamblado: EricksonLopez.Outbox
public sealed class OutboxMetrics : IDisposable
Implementa: IDisposable

Provides strongly typed OpenTelemetry meters and instruments for the Outbox pattern.

Notas:

All instruments follow OpenTelemetry semantic conventions for messaging. Static Meter — Design Decision: `Meter` is a static global field following the same pattern used by .NET runtime metrics (e.g., `System.Net.Http`, `System.Runtime`). For a library (not an application), static meters are the established approach per the OpenTelemetry .NET guidance. Test isolation: Because the `Meter` is static, counter values accumulate across test runs within the same process. Tests that assert on metric values should use: - `MeterListener` (built-in, zero-dependency): subscribe to the meter before the operation under test and assert on recorded values within the listener scope. - `OpenTelemetry.Testing` / `InMemoryExporter`: configure a scoped exporter per-test to capture only that test's metrics. IMeterFactory alternative (deferred): DI-scoped meters via `IMeterFactory` (.NET 8+) would provide automatic test isolation. This was evaluated but deferred because: it would require passing `IMeterFactory` through `AdaptivePoller`, `OutboxChannel`, and all consumers — a significant API surface change for a benefit that's primarily relevant to testing. This will be revisited in v2.0. AUDIT-FIX P1-E — Cardinality warning for `message_type` tag: Several histograms and counters use a `message_type` tag (the alias string from `[OutboxMessage("your.alias")]`). Each unique alias creates a separate time series in your metrics backend (Prometheus, OTEL Collector, etc.). With N distinct message types, each tagged instrument creates N time series. For 10 message types across 6 instruments = 60 active time series — acceptable. For 100+ message types across 6 instruments = 600+ active time series — may cause cardinality issues in Prometheus with default limits (default: 10,000 series). If cardinality becomes a concern, consider: - Using short, stable aliases (e.g., `"order.created.v1"`) instead of FQDN-style names. - Setting `OutboxRuntimeOptions.IncludeMessageTypeTag = false` to omit the tag entirely from all metrics. - Configuring Prometheus relabeling to drop the tag at the scrape level.

Miembros (16)

  • constructorOutboxMetrics
    public OutboxMetrics(IMeterFactory? meterFactory = null)

    Initializes a new instance of the `OutboxMetrics` class.

    meterFactory: IMeterFactory?
    An optional meter factory to resolve the meter instance.
  • methodCreateChannelFillGauge
    public ObservableGauge<double> CreateChannelFillGauge(Func<int> countProvider, int capacity)

    Creates an observable gauge to monitor the fill ratio of the outbox dispatch channel.

    countProvider: Func<int>
    A function that returns the current number of items in the channel.
    capacity: int
    The maximum capacity of the channel.

    Retorna: An observable gauge measuring the channel fill ratio.

  • methodDispose
    public void Dispose()

    Disposes the underlying meter instance and releases associated resources.

  • methodRecordStoreDuration
    public void RecordStoreDuration(double seconds, string messageType)

    Records the time taken to store a message or batch in the database.

    seconds: double
    The duration in seconds.
    messageType: string
    The message type alias or 'batch'.
  • propertyBatchSize
    public Histogram<int> BatchSize { get; }

    Gets the histogram tracking the number of messages fetched in a single database polling batch.

  • propertyDeadLettersTotal
    public Counter<long> DeadLettersTotal { get; }

    Gets the counter tracking the total number of messages moved to the dead-letter queue after exhausting all retry attempts.

  • propertyDispatchDuration
    public Histogram<double> DispatchDuration { get; }

    Gets the histogram tracking the time taken by the broker publisher to send a single message over the network.

  • propertyDispatchFailures
    public Counter<long> DispatchFailures { get; }

    Gets the counter tracking the total dispatch failures (transient + fatal combined).

  • propertyDlqInsertFailures
    public Counter<long> DlqInsertFailures { get; }

    Gets the counter tracking the total number of DLQ INSERT failures.

    A non-zero value means a message was dead-lettered in the outbox table (state=4) but the corresponding record could NOT be written to the dead-letter table (e.g., the DLQ table does not exist, or a constraint failed). The dead-letter data is lost from the DLQ, but the outbox message will not be re-processed. Monitor for spikes and set alerts.

  • propertyMessagesDispatched
    public Counter<long> MessagesDispatched { get; }

    Gets the counter tracking the total number of messages successfully dispatched to the broker.

  • propertyMeter
    public Meter Meter { get; }

    Gets the meter instance used to create OpenTelemetry instruments.

  • propertyQueueDuration
    public Histogram<double> QueueDuration { get; }

    Gets the histogram tracking the time elapsed between message creation and its dispatch attempt (queue latency).

  • propertyReclaimedMessages
    public Counter<long> ReclaimedMessages { get; }

    Gets the counter tracking the total number of messages reclaimed from the 'InFlight' state due to dispatcher crashes or timeouts.

  • propertyRetryAttemptsTotal
    public Counter<long> RetryAttemptsTotal { get; }

    Gets the counter tracking the total number of retry attempts performed by the dispatcher.

  • propertyStoreDuration
    public Histogram<double> StoreDuration { get; }

    Gets the histogram tracking the time taken to build and store a message into the database.

  • fieldMeterName
    public const string MeterName

    Gets the canonical name of the Outbox meter.

EricksonLopez.Outbox.Dispatcher#

1
interface

IPollerWakeup

Ensamblado: EricksonLopez.Outbox
public interface IPollerWakeup

Defines a contract that allows external notification systems (e.g., PostgreSQL LISTEN/NOTIFY) to wake the dispatcher poller without creating a hard dependency on concrete poller implementations.

Notas:

Decoupling the notification listener from the concrete poller allows: - Testing the listener in isolation with a mock wakeup implementation. - Substituting the poller with future alternative implementations (e.g., priority poller). - Removing the transitive dependency of PostgreSQL storage on the core dispatcher internals.

Miembros (1)

  • methodWakeUp
    void WakeUp()

    Signals the poller to wake up and begin a fetch cycle immediately, bypassing the configured polling interval.

    Must be safe to call from any thread and any context (e.g., a background notification callback). It must not throw under any circumstances, including if the poller has already been woken up.

EricksonLopez.Outbox.EntityFrameworkCore#

5
class

EntityFrameworkCoreDeadLetterRepository<TDbContext>

Ensamblado: EricksonLopez.Outbox.EntityFrameworkCore
public class EntityFrameworkCoreDeadLetterRepository<TDbContext> : IDeadLetterRepository where TDbContext : DbContext
Implementa: IDeadLetterRepository

Provides an Entity Framework Core implementation of `IDeadLetterRepository`.

Notas:

Type parameters: TDbContext: The application's `DbContext` type that contains outbox entities.

Miembros (6)

  • constructorEntityFrameworkCoreDeadLetterRepository
    public EntityFrameworkCoreDeadLetterRepository(IServiceProvider serviceProvider)

    Initializes a new instance of the `EntityFrameworkCoreDeadLetterRepository<TDbContext>` class.

    serviceProvider: IServiceProvider
    The service provider to resolve scoped DbContext instances.

    Exceptions: ArgumentNullException: `serviceProvider` is `null`

  • methodDeleteAsync
    public async ValueTask DeleteAsync(Guid id, CancellationToken cancellationToken = default)

    Deletes a dead-lettered message by its unique identifier.

    id: Guid
    The unique identifier of the dead-lettered message to delete.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • methodGetAsync
    public async ValueTask<IReadOnlyList<DeadLetterMessage>> GetAsync(int limit = 100, DateTimeOffset? after = null, CancellationToken cancellationToken = default)

    Retrieves a page of dead-lettered messages for inspection or replay.

    limit: int
    The maximum number of records to return.
    after: DateTimeOffset?
    The cursor indicating to return records dead-lettered after this timestamp. Pass `DateTimeOffset.MinValue` for the first page.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the retrieved page of dead-lettered messages.

  • methodInsertAsync
    public async ValueTask InsertAsync(DeadLetterMessage message, EricksonLopez.Outbox.Persistence.IOutboxTransactionContext? transaction, CancellationToken cancellationToken = default)

    Persists a dead-lettered message.

    message: DeadLetterMessage
    The dead-lettered message to persist.
    transaction: EricksonLopez.Outbox.Persistence.IOutboxTransactionContext?
    The optional transaction context. If `null`, the repository must open its own connection and auto-commit the insert.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Called by the Dispatcher after a message has exhausted its `Retry.RetryPolicy`.

  • methodPurgeAsync
    public async ValueTask PurgeAsync(DateTimeOffset olderThan, CancellationToken cancellationToken = default)

    Purges all dead-lettered messages older than the specified timestamp.

    olderThan: DateTimeOffset
    The timestamp threshold; messages older than this value will be purged.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • propertyIsFirstPartyImplementation
    public bool IsFirstPartyImplementation { get; }

    Gets a value indicating whether this is a first-party (built-in) implementation.

    Used by `OutboxStartupValidator` to warn operators when a third-party `IDeadLetterRepository` is registered, reminding them to verify that their implementation correctly handles `transaction = null` (auto-commit mode). All first-party storage engine implementations override this to return `true`. Third-party implementations that do not override this will return `false`, triggering the startup advisory log message. This is a Zero-Reflection pattern: no `GetType().Name`, no string comparisons, no assembly scanning. The check is a simple virtual dispatch.

class

EntityFrameworkCoreIdempotencyRepository<TDbContext>

Ensamblado: EricksonLopez.Outbox.EntityFrameworkCore
public class EntityFrameworkCoreIdempotencyRepository<TDbContext> : IIdempotencyRepository where TDbContext : DbContext
Implementa: IIdempotencyRepository

Provides an Entity Framework Core implementation of `IIdempotencyRepository`.

Notas:

Type parameters: TDbContext: The application's `DbContext` type that contains idempotency records.

Miembros (3)

  • constructorEntityFrameworkCoreIdempotencyRepository
    public EntityFrameworkCoreIdempotencyRepository(IServiceProvider serviceProvider)

    Initializes a new instance of the `EntityFrameworkCoreIdempotencyRepository<TDbContext>` class.

    serviceProvider: IServiceProvider
    The service provider to resolve scoped DbContext instances.

    Exceptions: ArgumentNullException: `serviceProvider` is `null`

  • methodPurgeExpiredRecordsAsync
    public async ValueTask PurgeExpiredRecordsAsync(DateTimeOffset olderThan, CancellationToken cancellationToken = default)

    Purges idempotency records older than the specified timestamp.

    olderThan: DateTimeOffset
    The timestamp threshold; records older than this value will be purged.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Called periodically by `InboxCleanupService` to prevent table bloat.

  • methodTryInsertAsync
    public async ValueTask<bool> TryInsertAsync(IdempotencyRecord record, EricksonLopez.Outbox.Persistence.IOutboxTransactionContext? transaction = default, CancellationToken cancellationToken = default)

    Attempts to insert an idempotency record.

    record: IdempotencyRecord
    The idempotency record to insert.
    transaction: EricksonLopez.Outbox.Persistence.IOutboxTransactionContext?
    The optional transaction context.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result is `true` if the record was inserted; otherwise, `false` if the record already exists (duplicate).

class

EntityFrameworkCoreOutboxRepository<TDbContext>

Ensamblado: EricksonLopez.Outbox.EntityFrameworkCore
public class EntityFrameworkCoreOutboxRepository<TDbContext> : IOutboxRepository where TDbContext : DbContext
Implementa: IOutboxRepository

Provides an Entity Framework Core implementation of `IOutboxRepository`. Operates on a `TDbContext` to participate directly in EF Core transactions.

Notas:

Type parameters: TDbContext: The application's `DbContext` type that owns the outbox tables.

Miembros (9)

  • constructorEntityFrameworkCoreOutboxRepository
    public EntityFrameworkCoreOutboxRepository(IServiceProvider serviceProvider, TimeProvider? timeProvider = null)

    Initializes a new instance of the `EntityFrameworkCoreOutboxRepository<TDbContext>` class.

    serviceProvider: IServiceProvider
    The service provider to resolve scoped DbContext instances.
    timeProvider: TimeProvider?
    The time provider for time-based queries.

    Exceptions: ArgumentNullException: `serviceProvider` is `null`

  • methodFetchPendingAsync
    public async ValueTask<IReadOnlyList<OutboxMessage>> FetchPendingAsync(int batchSize, CancellationToken cancellationToken = default)

    Retrieves a batch of pending messages ready for delivery.

    batchSize: int
    The maximum number of messages to retrieve.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the batch of messages retrieved.

    The method fetches up to the specified batch size of messages that are in the Pending state (0) and whose delivery time is less than or equal to the current UTC time. Implementations guarantee safe concurrent polling by using SKIP LOCKED or equivalent semantics, atomically transitioning the fetched messages to the InFlight state (1). Scheduling edge case — `deliver_at` vs `MaxMessageAge`: Messages stored with a future `deliver_at` timestamp that exceeds `MaxMessageAge` will be silently excluded from polling by the `created_at` age guard. Such messages will not be processed and will not be automatically dead-lettered. Ensure `OutboxRuntimeOptions.MaxMessageAge` is greater than the maximum `deliver_at` offset used in your application (e.g., if scheduling up to 7 days ahead, set `MaxMessageAge ≥ 8 days`). Ordering with multiple dispatcher instances: When multiple dispatcher instances run concurrently, messages are fetched in `ORDER BY created_at ASC, id ASC` order but can be claimed by different instances via `SKIP LOCKED`, resulting in non-deterministic global ordering. In partitioned table setups, the order guarantee applies within each partition only. For strict global ordering, use a single dispatcher instance with `MaxDegreeOfParallelism = 1`.

  • methodGetPendingCountAsync
    public async ValueTask<long> GetPendingCountAsync(CancellationToken cancellationToken = default)

    Retrieves the approximate count of messages awaiting processing.

    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the approximate pending message count.

    Includes messages in the Pending (0) or Failed (3) states for metrics and monitoring.

  • methodInsertAsync
    public ValueTask InsertAsync(OutboxMessage record, EricksonLopez.Outbox.Persistence.IOutboxTransactionContext transaction, CancellationToken cancellationToken = default)

    Inserts a single message into the outbox table atomically within the specified transaction.

    record: OutboxMessage
    The message to insert into the outbox.
    transaction: EricksonLopez.Outbox.Persistence.IOutboxTransactionContext
    The context representing the active database transaction.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • methodInsertBatchAsync
    public ValueTask InsertBatchAsync(ReadOnlyMemory<OutboxMessage> records, EricksonLopez.Outbox.Persistence.IOutboxTransactionContext transaction, CancellationToken cancellationToken = default)

    Inserts a batch of messages into the outbox table in a single round-trip.

    records: ReadOnlyMemory<OutboxMessage>
    The batch of messages to insert.
    transaction: EricksonLopez.Outbox.Persistence.IOutboxTransactionContext
    The context representing the active database transaction.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Implementations should use bulk insert mechanisms (e.g., COPY, UNNEST, or table-valued parameters). If native bulk insert is unavailable, implementations fall back to individual inserts.

  • methodMarkAsDispatchedAsync
    public async ValueTask MarkAsDispatchedAsync(IReadOnlyList<OutboxMessage> messages, CancellationToken cancellationToken = default)

    Atomically marks the specified messages as successfully dispatched.

    messages: IReadOnlyList<OutboxMessage>
    The collection of messages to mark as dispatched.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • methodMarkAsFailedAsync
    public async ValueTask MarkAsFailedAsync(IReadOnlyList<OutboxMessage> messages, string error, bool isDeadLetter = false, CancellationToken cancellationToken = default)

    Marks the specified messages as failed, updating their error details and retry counts.

    messages: IReadOnlyList<OutboxMessage>
    The collection of messages that failed to process.
    error: string
    The error message or exception details causing the failure.
    isDeadLetter: bool
    `true` to mark the messages as permanently failed (dead letter); otherwise, `false`.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Is typically invoked by `Retry.RetryDispatcherInterceptor` when publishing fails. If the maximum retry attempts are exhausted, the message may be marked as a dead letter. Security Warning: The `error` parameter may contain sensitive information (such as connection strings in stack traces). Ensure exceptions are sanitized in production environments before they are persisted, to prevent leaking sensitive data.

  • methodPurgeDispatchedMessagesAsync
    public async ValueTask<int> PurgeDispatchedMessagesAsync(DateTimeOffset cutoff, int batchSize = 1000, CancellationToken cancellationToken = default)

    Purges dispatched messages that were processed prior to the specified cutoff timestamp. Used by `Hosting.OutboxCleanupService` when `DeleteOnDispatch = false`.

    cutoff: DateTimeOffset
    The cutoff timestamp; messages dispatched prior to this time will be deleted.
    batchSize: int
    The maximum number of rows to delete in a single batch.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation, returning the number of purged rows.

  • methodReclaimStaleMessagesAsync
    public async ValueTask<int> ReclaimStaleMessagesAsync(TimeSpan staleTimeout, CancellationToken cancellationToken = default)

    Reclaims messages that have remained in the InFlight state longer than the specified timeout.

    staleTimeout: TimeSpan
    The duration after which an InFlight message is considered abandoned.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the number of messages reclaimed.

    This mechanism prevents message loss if a dispatcher crashes after claiming a batch (transitioning from state 0 to 1) but before marking it as dispatched. Implementations must atomically reset these messages to the Pending state (0) if their last updated time is older than the current UTC time minus the stale timeout.

class

OutboxEntityFrameworkCoreSetup

Ensamblado: EricksonLopez.Outbox.EntityFrameworkCore
public static class OutboxEntityFrameworkCoreSetup

Provides extension methods for registering Entity Framework Core persistence services for the outbox.

Miembros (1)

  • methodAddOutboxEntityFrameworkCore<TDbContext>
    public static IServiceCollection AddOutboxEntityFrameworkCore<TDbContext>(this IServiceCollection services) where TDbContext : DbContext

    Registers Entity Framework Core outbox persistence repositories for the specified `TDbContext` type.

    services: this IServiceCollection
    The service collection to add the repositories to.

    Retorna: The modified `IServiceCollection` for chaining.

    Type parameters: TDbContext: The application `DbContext` type that owns the outbox tables. Exceptions: ArgumentNullException: `services` is `null`

class

OutboxModelBuilderExtensions

Ensamblado: EricksonLopez.Outbox.EntityFrameworkCore
public static class OutboxModelBuilderExtensions

Provides extension methods for configuring Entity Framework Core entity mappings for the outbox tables.

Miembros (1)

  • methodApplyOutboxEntityConfigurations
    public static ModelBuilder ApplyOutboxEntityConfigurations(this ModelBuilder modelBuilder, string schema = "")

    Applies entity type configurations for `Entities.OutboxMessageEntity`, `Entities.IdempotencyRecordEntity`, and `Entities.DeadLetterMessageEntity` to the provided `ModelBuilder`.

    modelBuilder: this ModelBuilder
    The EF Core model builder to configure.
    schema: string
    The database schema that contains the outbox tables. Defaults to `"outbox"`.

    Retorna: The same `ModelBuilder` instance to allow further fluent configuration calls.

    Exceptions: ArgumentNullException: `modelBuilder` is `null`

EricksonLopez.Outbox.EntityFrameworkCore.Entities#

3
class

DeadLetterMessageEntity

Ensamblado: EricksonLopez.Outbox.EntityFrameworkCore
public class DeadLetterMessageEntity

Represents an Entity Framework Core database entity for a dead letter message.

Miembros (14)

  • methodFromModel
    public static DeadLetterMessageEntity FromModel(DeadLetterMessage model)

    Creates a new `DeadLetterMessageEntity` from the domain `DeadLetterMessage` model.

    model: DeadLetterMessage
    The domain model to convert.

    Retorna: A new `DeadLetterMessageEntity` instance.

  • methodToModel
    public DeadLetterMessage ToModel()

    Converts the entity into the domain `DeadLetterMessage` model.

    Retorna: A new `DeadLetterMessage` instance.

  • propertyCausationId
    public string? CausationId { get; set; }

    Gets or sets the causation identifier.

  • propertyCorrelationId
    public string? CorrelationId { get; set; }

    Gets or sets the correlation identifier.

  • propertyCreatedAt
    public DateTimeOffset CreatedAt { get; set; }

    Gets or sets the timestamp when the original message was created.

  • propertyDeadLetteredAt
    public DateTimeOffset DeadLetteredAt { get; set; }

    Gets or sets the timestamp when the message was moved to the dead letter queue.

  • propertyHeadersJson
    public string HeadersJson { get; set; }

    Gets or sets the headers in JSON format.

  • propertyId
    public Guid Id { get; set; }

    Gets or sets the dead letter identifier.

  • propertyLastError
    public string? LastError { get; set; }

    Gets or sets the last error encountered during processing.

  • propertyMessageType
    public string MessageType { get; set; }

    Gets or sets the message type.

  • propertyOriginalMessageId
    public Guid OriginalMessageId { get; set; }

    Gets or sets the original message identifier.

  • propertyPayload
    public byte[] Payload { get; set; }

    Gets or sets the message payload.

  • propertyReason
    public string Reason { get; set; }

    Gets or sets the reason the message was dead lettered.

  • propertyRetryCount
    public int RetryCount { get; set; }

    Gets or sets the number of retry attempts.

class

IdempotencyRecordEntity

Ensamblado: EricksonLopez.Outbox.EntityFrameworkCore
public class IdempotencyRecordEntity

Represents an Entity Framework Core database entity for an inbox idempotency record.

Miembros (5)

  • methodFromModel
    public static IdempotencyRecordEntity FromModel(IdempotencyRecord model)

    Creates a new `IdempotencyRecordEntity` from the domain `IdempotencyRecord` model.

    model: IdempotencyRecord
    The domain model to convert.

    Retorna: A new `IdempotencyRecordEntity` instance.

  • methodToModel
    public IdempotencyRecord ToModel()

    Converts the entity into the domain `IdempotencyRecord` model.

    Retorna: A new `IdempotencyRecord` instance.

  • propertyConsumerId
    public string ConsumerId { get; set; }

    Gets or sets the consumer identifier.

  • propertyMessageId
    public string MessageId { get; set; }

    Gets or sets the message identifier.

  • propertyProcessedAt
    public DateTimeOffset ProcessedAt { get; set; }

    Gets or sets the timestamp when the message was processed.

class

OutboxMessageEntity

Ensamblado: EricksonLopez.Outbox.EntityFrameworkCore
public class OutboxMessageEntity

Represents an Entity Framework Core database entity for an outbox message.

Miembros (14)

  • methodFromModel
    public static OutboxMessageEntity FromModel(OutboxMessage model)

    Creates a new `OutboxMessageEntity` from the domain `OutboxMessage` model.

    model: OutboxMessage
    The domain model to convert.

    Retorna: A new `OutboxMessageEntity` instance.

  • methodToModel
    public OutboxMessage ToModel()

    Converts the entity into the domain `OutboxMessage` model.

    Retorna: A new `OutboxMessage` instance.

  • propertyCausationId
    public string? CausationId { get; set; }

    Gets or sets the causation identifier.

  • propertyCorrelationId
    public string? CorrelationId { get; set; }

    Gets or sets the correlation identifier.

  • propertyCreatedAt
    public DateTimeOffset CreatedAt { get; set; }

    Gets or sets the timestamp when the message was created.

  • propertyDeliverAt
    public DateTimeOffset? DeliverAt { get; set; }

    Gets or sets the timestamp when the message should be delivered.

  • propertyError
    public string? Error { get; set; }

    Gets or sets the error encountered during processing.

  • propertyHeadersJson
    public string HeadersJson { get; set; }

    Gets or sets the headers in JSON format.

  • propertyId
    public Guid Id { get; set; }

    Gets or sets the message identifier.

  • propertyMessageType
    public string MessageType { get; set; }

    Gets or sets the message type.

  • propertyPayload
    public byte[] Payload { get; set; }

    Gets or sets the message payload.

  • propertyProcessedAt
    public DateTimeOffset? ProcessedAt { get; set; }

    Gets or sets the timestamp when the message was processed.

  • propertyRetryCount
    public int RetryCount { get; set; }

    Gets or sets the number of retry attempts.

  • propertyState
    public int State { get; set; }

    Gets or sets the state of the message.

EricksonLopez.Outbox.Events#

4
class

EventsOutboxServiceCollectionExtensions

Ensamblado: EricksonLopez.Outbox.Events
public static class EventsOutboxServiceCollectionExtensions

Provides extension methods for registering `OutboxEventPublisher` with dependency injection.

Miembros (2)

  • methodAddOutboxEventPublisher
    public static IServiceCollection AddOutboxEventPublisher(this IServiceCollection services)

    Registers the `OutboxEventPublisher` as the implementation for `IEventPublisher`.

    services: this IServiceCollection
    The `IServiceCollection` to configure.

    Retorna: The configured `IServiceCollection` instance.

    Exceptions: ArgumentNullException: `services` is `null`

  • methodAddOutboxEventPublisher<TTransactionProvider>
    public static IServiceCollection AddOutboxEventPublisher<TTransactionProvider>(this IServiceCollection services) where TTransactionProvider : class, IOutboxTransactionProvider

    Registers the `OutboxEventPublisher` along with a custom `TTransactionProvider`.

    services: this IServiceCollection
    The `IServiceCollection` to configure.

    Retorna: The configured `IServiceCollection` instance.

    Type parameters: TTransactionProvider: The type of the custom transaction provider. Exceptions: ArgumentNullException: `services` is `null`

interface

IOutboxTransactionProvider

Ensamblado: EricksonLopez.Outbox.Events
public interface IOutboxTransactionProvider

Defines a provider that accesses the active `IOutboxTransactionContext` for outbox persistence.

Miembros (1)

  • propertyCurrentTransaction
    IOutboxTransactionContext? CurrentTransaction { get; }

    Gets the current active transaction context, or `null` if no transaction is active.

class

NullOutboxTransactionProvider

Ensamblado: EricksonLopez.Outbox.Events
public sealed class NullOutboxTransactionProvider : IOutboxTransactionProvider
Implementa: IOutboxTransactionProvider

Provides a no-op implementation of `IOutboxTransactionProvider` when no ambient transaction is managed.

Miembros (2)

  • propertyCurrentTransaction
    public IOutboxTransactionContext? CurrentTransaction { get; }

    Gets the current active transaction context, or `null` if no transaction is active.

  • propertyInstance
    public static NullOutboxTransactionProvider Instance { get; }

    Gets the singleton instance of `NullOutboxTransactionProvider`.

class

OutboxEventPublisher

Ensamblado: EricksonLopez.Outbox.Events
public sealed class OutboxEventPublisher : IEventPublisher
Implementa: IEventPublisher

Provides event publishing by atomically storing events into a transactional outbox.

Miembros (2)

  • constructorOutboxEventPublisher
    public OutboxEventPublisher(IOutbox outbox, IOutboxTransactionProvider? transactionProvider = null)

    Initializes a new instance of the `OutboxEventPublisher` class with the specified outbox service and transaction provider.

    outbox: IOutbox
    The outbox persistence service.
    transactionProvider: IOutboxTransactionProvider?
    The optional transaction provider. If `null`, defaults to `NullOutboxTransactionProvider.Instance`.

    Exceptions: ArgumentNullException: `outbox` is `null`

  • methodPublishAsync<TEvent>
    public ValueTask PublishAsync<TEvent>(TEvent eventInstance, CancellationToken cancellationToken = default) where TEvent : IEvent

    Inherits documentation from base type or interface.

    eventInstance: TEvent
    cancellationToken: CancellationToken

    Exceptions: ArgumentNullException: `eventInstance` is `null`; InvalidOperationException: No active transaction context was provided by the transaction provider

EricksonLopez.Outbox.Hosting#

4
class

ManualOutboxDispatcher

Ensamblado: EricksonLopez.Outbox
public sealed class ManualOutboxDispatcher

Provides the ability to manually dispatch messages instead of relying on the background poller.

Notas:

This service is particularly useful in serverless environments or for scenarios where dispatching must be triggered via an external signal (e.g., a Web API call or Cron Job). The dispatcher operates synchronously in its trigger but executes asynchronously.

Miembros (2)

  • constructorManualOutboxDispatcher
    public ManualOutboxDispatcher(IServiceProvider serviceProvider, IBrokerPublisher publisher, IOutboxMessageTypeResolver typeResolver)

    Initializes a new instance of the `ManualOutboxDispatcher` class.

    serviceProvider: IServiceProvider
    The dependency injection service provider.
    publisher: IBrokerPublisher
    The broker publisher responsible for transmitting messages.
    typeResolver: IOutboxMessageTypeResolver
    The resolver used to map message aliases to concrete CLR types.

    Exceptions: ArgumentNullException: Any of the provided arguments is `null`

  • methodDispatchPendingAsync
    public async Task<int> DispatchPendingAsync(IOutboxRepository repository, int batchSize = 50, CancellationToken cancellationToken = default)

    Fetches up to the specified number of pending messages and dispatches them immediately.

    repository: IOutboxRepository
    The outbox repository from which pending messages are fetched.
    batchSize: int
    The maximum number of messages to fetch and dispatch in this run.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task that represents the asynchronous operation. The task result contains the number of messages successfully dispatched.

    Exceptions: ArgumentNullException: `repository` is `null`; ArgumentOutOfRangeException: `batchSize` is zero or negative

class

OutboxCleanupService

Ensamblado: EricksonLopez.Outbox
public sealed class OutboxCleanupService : BackgroundService
Hereda de: BackgroundService

Background service that periodically purges dispatched outbox messages when soft-delete mode (`DeleteOnDispatch = false`) is active.

Miembros (2)

  • constructorOutboxCleanupService
    public OutboxCleanupService(IServiceProvider serviceProvider, IOptions<OutboxCleanupOptions> options, ILogger<OutboxCleanupService> logger, TimeProvider? timeProvider = null)

    Initializes a new instance of the `OutboxCleanupService` class.

    serviceProvider: IServiceProvider
    The service provider used to resolve scoped repository instances.
    options: IOptions<OutboxCleanupOptions>
    The cleanup options governing retention and interval.
    logger: ILogger<OutboxCleanupService>
    The logger instance.
    timeProvider: TimeProvider?
    Optional time provider for testing and clock virtualization.
  • methodPerformCleanupAsync
    public async Task<int> PerformCleanupAsync(CancellationToken cancellationToken = default)

    Executes a single purge pass. Can be called directly for on-demand cleanup or testing.

    cancellationToken: CancellationToken
    The cancellation token.

    Retorna: The number of purged messages, or 0 if no repository is registered.

class

OutboxHealthCheck

Ensamblado: EricksonLopez.Outbox
public sealed class OutboxHealthCheck : IHealthCheck
Implementa: IHealthCheck

Provides an ASP.NET Core Health Check implementation for the Outbox subsystem.

Notas:

This health check reports the current state of the dispatcher background service and the number of pending messages in the outbox. Health status logic: - Healthy: Dispatcher is running, and pending messages are ≤ `OutboxHealthCheckOptions.WarningThreshold`. - Degraded: Dispatcher is running but pending messages reach or exceed the threshold. - Unhealthy: Dispatcher is not running, or retrieving the pending count failed. Producer-only deployments: If no `OutboxDispatcherBackgroundService` is registered, the health check inherently assumes a producer-only pattern. It will report Healthy and include a note that no dispatcher is configured for this specific process.

Miembros (2)

  • constructorOutboxHealthCheck
    public OutboxHealthCheck(IServiceProvider serviceProvider, IOutboxRepository repository, IOptions<OutboxHealthCheckOptions> options)

    Initializes a new instance of the `OutboxHealthCheck` class.

    serviceProvider: IServiceProvider
    The dependency injection container to optionally resolve the dispatcher.
    repository: IOutboxRepository
    The repository used to query pending outbox messages.
    options: IOptions<OutboxHealthCheckOptions>
    The configured health check options, including warning thresholds.
  • methodCheckHealthAsync
    public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)

    Evaluates the health status of the outbox subsystem.

    context: HealthCheckContext
    The health check context.
    cancellationToken: CancellationToken
    A token that can be used to cancel the health check operation.

    Retorna: A task that represents the asynchronous health check operation, containing the `HealthCheckResult`.

class

OutboxServiceCollectionExtensions

Ensamblado: EricksonLopez.Outbox
public static class OutboxServiceCollectionExtensions

Extension methods for registering and configuring EricksonLopez.Outbox services within an `IServiceCollection`.

Miembros (3)

  • methodAddOutbox
    public static IServiceCollection AddOutbox(this IServiceCollection services, Action<OutboxOptions>? configure = null)

    Registers all core Outbox services, including the producer API and optional dispatcher components.

    services: this IServiceCollection
    The service collection to add the outbox services to.
    configure: Action<OutboxOptions>?
    An optional action to configure the `OutboxOptions`.

    Retorna: The modified `IServiceCollection` for chaining.

    Is idempotent: it uses `TryAddSingleton` and `TryAddScoped` internally. Calling it multiple times or in combination with `AddOutboxDispatcher` will NOT result in duplicate service registrations. Producer-only pattern: Call `AddOutbox` without subsequently configuring the dispatcher if this application only writes messages to the outbox database, leaving the dispatch responsibility to a separate worker process.

  • methodAddOutboxDispatcher
    public static IServiceCollection AddOutboxDispatcher(this IServiceCollection services, Action<OutboxDispatcherOptions>? configure = null)

    Explicitly registers and configures the Outbox dispatcher infrastructure and polling background services.

    services: this IServiceCollection
    The service collection to add the dispatcher services to.
    configure: Action<OutboxDispatcherOptions>?
    An optional action to configure the `OutboxDispatcherOptions`.

    Retorna: The modified `IServiceCollection` for chaining.

    Is idempotent and safely co-exists with `AddOutbox`. Use when you need to provide specific configurations for the background dispatcher, such as max parallelism or batch sizes, distinct from the core outbox producer configuration. Note on concurrency: The outbox uses native database locking (e.g., `FOR UPDATE SKIP LOCKED`) to handle multi-instance concurrent polling safely and efficiently. Advanced mechanisms like `ILeaseManager` and distributed locks are completely optional and generally unnecessary unless you need strict leader-election topologies.

  • methodAddOutboxInbox
    public static IServiceCollection AddOutboxInbox(this IServiceCollection services, Action<OutboxInboxOptions>? configure = null)

    Registers the Inbox idempotency services, including the background cleanup service.

    services: this IServiceCollection
    The service collection to add the inbox services to.
    configure: Action<OutboxInboxOptions>?
    An optional action to configure the `OutboxInboxOptions`.

    Retorna: The modified `IServiceCollection` for chaining.

EricksonLopez.Outbox.Idempotency#

3
interface

IInboxIdempotencyChecker

Ensamblado: EricksonLopez.Outbox
public interface IInboxIdempotencyChecker

Provides idempotency verification for incoming messages.

Miembros (2)

  • methodShouldProcessAsync
    Task<bool> ShouldProcessAsync(string messageId, string consumerId, IOutboxTransactionContext transaction, CancellationToken cancellationToken = default)

    Determines whether a message should be processed by attempting to insert its idempotency record.

    messageId: string
    The unique identifier of the incoming message.
    consumerId: string
    The unique identifier of the consumer processing the message.
    transaction: IOutboxTransactionContext
    The active transaction context coordinating the idempotency check and the business operation.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: `true` if the record was successfully inserted and the message should be processed; otherwise, `false`.

    Transaction Isolation Note: Relies on the underlying database's atomic insert capabilities (e.g., ON CONFLICT DO NOTHING) to prevent race conditions (TOCTOU). This is completely safe under READ COMMITTED. However, if the provided `IOutboxTransactionContext` uses the `SERIALIZABLE` isolation level, concurrent inserts for the same message ID across different transactions may result in a serialization failure exception (e.g., SQL Server error 1205 or PostgreSQL 40001) instead of a graceful skip. Consumers using `SERIALIZABLE` must be prepared to catch and retry these specific transaction abort exceptions at the application level.

  • methodShouldSkipAsync
    Task<bool> ShouldSkipAsync(Guid messageId, IOutboxTransactionContext transaction, string consumerId = OutboxConstants.DispatcherConsumerId, CancellationToken cancellationToken = default)

    Determines whether a specific message has already been processed and should be skipped.

    messageId: Guid
    The unique identifier of the message.
    transaction: IOutboxTransactionContext
    The active transaction context coordinating the check.
    consumerId: string
    A unique, stable identifier for the consumer performing the check. Defaults to `OutboxConstants.DispatcherConsumerId` for dispatcher-internal use. Provide a consumer-specific ID (e.g., `"order-service.payment-handler"`) when calling from user-facing consumers.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: `true` if the message has already been processed; otherwise, `false`.

    Uses a database insert to atomically detect duplicates. The `consumerId` identifies which consumer is performing the check. Always use a unique, stable consumer ID per consumer in your application to avoid collision with other consumers' records. Warning: Do not reuse `OutboxConstants.DispatcherConsumerId` in your own consumers. That ID is reserved for the outbox dispatcher's internal deduplication. Reusing it would cause your consumer's records to collide with the dispatcher's, resulting in incorrect duplicate-detection behavior.

class

InboxCleanupService

Ensamblado: EricksonLopez.Outbox
public sealed class InboxCleanupService : BackgroundService
Hereda de: BackgroundService

Orchestrates the periodic cleanup of expired idempotency records in the background.

Notas:

This background service prevents the inbox idempotency table from growing indefinitely by routinely purging records older than the configured duplicate detection window.

Miembros (2)

  • constructorInboxCleanupService
    public InboxCleanupService(IServiceProvider serviceProvider, IOptions<OutboxInboxOptions> options, ILogger<InboxCleanupService> logger, TimeProvider? timeProvider = null)

    Initializes a new instance of the `InboxCleanupService` class.

    serviceProvider: IServiceProvider
    The dependency injection container that resolves repository instances.
    options: IOptions<OutboxInboxOptions>
    The configured inbox options governing retention periods.
    logger: ILogger<InboxCleanupService>
    The logger that records cleanup activity and errors.
    timeProvider: TimeProvider?
    Optional time provider for testing and clock virtualization.
  • methodPerformCleanupAsync
    public async Task<bool> PerformCleanupAsync(CancellationToken cancellationToken = default)

    Executes a single purge pass for expired idempotency records. Can be called directly for on-demand cleanup or testing.

    cancellationToken: CancellationToken
    The cancellation token.

    Retorna: `true` if a repository was found and purge executed; otherwise, `false`.

class

InboxIdempotencyChecker

Ensamblado: EricksonLopez.Outbox
public sealed class InboxIdempotencyChecker : IInboxIdempotencyChecker
Implementa: IInboxIdempotencyChecker

Provides idempotency verification for incoming messages using the configured `IIdempotencyRepository`.

Notas:

This checker is used to ensure exactly-once processing semantics by rejecting messages that have already been processed by a specific consumer.

Miembros (3)

  • constructorInboxIdempotencyChecker
    public InboxIdempotencyChecker(IIdempotencyRepository idempotencyRepository)

    Initializes a new instance of the `InboxIdempotencyChecker` class.

    idempotencyRepository: IIdempotencyRepository
    The repository that stores and verify idempotency records.
  • methodShouldProcessAsync
    public async Task<bool> ShouldProcessAsync(string messageId, string consumerId, IOutboxTransactionContext transaction, CancellationToken cancellationToken = default)

    Determines whether a message should be processed by attempting to insert its idempotency record.

    messageId: string
    The unique identifier of the incoming message.
    consumerId: string
    The unique identifier of the consumer processing the message.
    transaction: IOutboxTransactionContext
    The active transaction context coordinating the idempotency check and the business operation.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: `true` if the record was successfully inserted and the message should be processed; otherwise, `false`.

  • methodShouldSkipAsync
    public async Task<bool> ShouldSkipAsync(Guid messageId, IOutboxTransactionContext transaction, string consumerId = OutboxConstants.DispatcherConsumerId, CancellationToken cancellationToken = default)

    Determines whether a specific message has already been processed and should be skipped.

    messageId: Guid
    The unique identifier of the message.
    transaction: IOutboxTransactionContext
    The active transaction context coordinating the check.
    consumerId: string
    The consumer identifier used to scope the idempotency check. Defaults to `OutboxConstants.DispatcherConsumerId` for dispatcher-internal use.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: `true` if the message has already been processed; otherwise, `false`.

EricksonLopez.Outbox.Inbox#

3
interface

IInboxConsumerFilter

Ensamblado: EricksonLopez.Outbox.Inbox
public interface IInboxConsumerFilter : EricksonLopez.Inbox.IInboxConsumerFilter
Implementa: EricksonLopez.Inbox.IInboxConsumerFilter

Defines an abstraction for consumer-side message deduplication and idempotent handler execution with optional transaction context.

Miembros (1)

  • methodExecuteIdempotentlyAsync
    ValueTask<bool> ExecuteIdempotentlyAsync(string messageId, string consumerName, Func<CancellationToken, ValueTask> handler, IOutboxTransactionContext? transaction = null, CancellationToken cancellationToken = default)

    Executes the given handler if and only if the message with `messageId` has not yet been processed by `consumerName`.

    messageId: string
    The unique incoming message identifier.
    consumerName: string
    The logical consumer or handler name.
    handler: Func<CancellationToken, ValueTask>
    The message processing delegate.
    transaction: IOutboxTransactionContext?
    The optional database transaction context.
    cancellationToken: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: `true` if the message was new and handled successfully; `false` if it was a duplicate and skipped.

class

InboxConsumerFilter

Ensamblado: EricksonLopez.Outbox.Inbox
public sealed class InboxConsumerFilter : IInboxConsumerFilter
Implementa: IInboxConsumerFilter

Provides consumer-side message deduplication backed by `IIdempotencyRepository`.

Miembros (2)

  • constructorInboxConsumerFilter
    public InboxConsumerFilter(IIdempotencyRepository idempotencyRepository, ILogger<InboxConsumerFilter> logger)

    Initializes a new instance of the `InboxConsumerFilter` class.

    idempotencyRepository: IIdempotencyRepository
    The repository used to record processed messages.
    logger: ILogger<InboxConsumerFilter>
    The logger instance.

    Exceptions: ArgumentNullException: `idempotencyRepository` or `logger` is `null`

  • methodExecuteIdempotentlyAsync
    public async ValueTask<bool> ExecuteIdempotentlyAsync(string messageId, string consumerName, Func<CancellationToken, ValueTask> handler, IOutboxTransactionContext? transaction = null, CancellationToken cancellationToken = default)

    Executes the given handler if and only if the message with `messageId` has not yet been processed by `consumerName`.

    messageId: string
    The unique incoming message identifier.
    consumerName: string
    The logical consumer or handler name.
    handler: Func<CancellationToken, ValueTask>
    The message processing delegate.
    transaction: IOutboxTransactionContext?
    The optional database transaction context.
    cancellationToken: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: `true` if the message was new and handled successfully; `false` if it was a duplicate and skipped.

class

InboxConsumerRegistrationExtensions

Ensamblado: EricksonLopez.Outbox.Inbox
public static class InboxConsumerRegistrationExtensions

Provides extension methods for registering inbox consumer idempotency services.

Miembros (1)

  • methodAddInboxDeduplication
    public static IServiceCollection AddInboxDeduplication(this IServiceCollection services)

    Registers the `InboxConsumerFilter` into the service collection.

    services: this IServiceCollection
    The service collection.

    Retorna: The modified service collection.

    Exceptions: ArgumentNullException: `services` is `null`

EricksonLopez.Outbox.Inbox.AspNetCore#

2
class

IdempotentEndpointFilter

Ensamblado: EricksonLopez.Outbox.Inbox.AspNetCore
public sealed class IdempotentEndpointFilter : IEndpointFilter
Implementa: IEndpointFilter

Provides a minimal API filter that enforces and processes HTTP requests idempotently via the `Idempotency-Key` header.

Miembros (2)

  • constructorIdempotentEndpointFilter
    public IdempotentEndpointFilter(string headerName = "")

    Initializes a new instance of `IdempotentEndpointFilter`.

    headerName: string
    The idempotency header name (default: `Idempotency-Key`).
  • methodInvokeAsync
    public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)

    Inherits documentation from base type or interface.

    context: EndpointFilterInvocationContext
    next: EndpointFilterDelegate
class

InboxAspNetCoreExtensions

Ensamblado: EricksonLopez.Outbox.Inbox.AspNetCore
public static class InboxAspNetCoreExtensions

Provides extension methods for registering and applying HTTP idempotency in ASP.NET Core pipelines.

Miembros (2)

  • methodRequireIdempotency
    public static RouteGroupBuilder RequireIdempotency(this RouteGroupBuilder builder, string headerName = "")

    Enforces idempotency tracking on this route group via the `Idempotency-Key` header.

    builder: this RouteGroupBuilder
    The route group builder.
    headerName: string
    The idempotency header name.

    Retorna: The route group builder for chaining.

    Exceptions: ArgumentNullException: `builder` is `null`

  • methodRequireIdempotency
    public static RouteHandlerBuilder RequireIdempotency(this RouteHandlerBuilder builder, string headerName = "")

    Enforces idempotency tracking on this endpoint via the `Idempotency-Key` header.

    builder: this RouteHandlerBuilder
    The route handler builder.
    headerName: string
    The idempotency header name.

    Retorna: The route handler builder for chaining.

    Exceptions: ArgumentNullException: `builder` is `null`

EricksonLopez.Outbox.Inbox.Events#

2
class

EventInboxServiceCollectionExtensions

Ensamblado: EricksonLopez.Outbox.Inbox.Events
public static class EventInboxServiceCollectionExtensions

Provides extension methods for registering idempotent event handling decorators in an `IServiceCollection`.

Miembros (1)

  • methodAddIdempotentEventHandler<TEvent, THandler>
    public static IServiceCollection AddIdempotentEventHandler<TEvent, THandler>(this IServiceCollection services, string? consumerName = null) where TEvent : class, IEvent where THandler : class, IEventHandler<TEvent>

    Decorates a registered `IEventHandler<TEvent>` with idempotent inbox execution.

    services: this IServiceCollection
    The `IServiceCollection` to configure.
    consumerName: string?
    The optional consumer name override.

    Retorna: The configured `IServiceCollection` instance.

    Type parameters: TEvent: The type of the event to handle.; THandler: The handler implementation type. Exceptions: ArgumentNullException: `services` is `null`

class

IdempotentEventHandler<TEvent>

Ensamblado: EricksonLopez.Outbox.Inbox.Events
public sealed class IdempotentEventHandler<TEvent> : IEventHandler<TEvent> where TEvent : IEvent
Implementa: IEventHandler<TEvent>

Decorates an `IEventHandler<TEvent>` with idempotent execution guarantees backed by `IInboxConsumerFilter`.

Notas:

Type parameters: TEvent: The event type.

Miembros (2)

  • constructorIdempotentEventHandler
    public IdempotentEventHandler(IEventHandler<TEvent> innerHandler, IInboxConsumerFilter inboxFilter, string? consumerName = null, ILogger<IdempotentEventHandler<TEvent>>? logger = null)

    Initializes a new instance of the `IdempotentEventHandler<TEvent>` class with the specified inner handler and inbox filter.

    innerHandler: IEventHandler<TEvent>
    The inner business event handler.
    inboxFilter: IInboxConsumerFilter
    The inbox consumer filter for deduplication.
    consumerName: string?
    The optional logical consumer name.
    logger: ILogger<IdempotentEventHandler<TEvent>>?
    The optional logger instance.

    Exceptions: ArgumentNullException: `innerHandler` or `inboxFilter` is `null`

  • methodHandleAsync
    public async ValueTask HandleAsync(TEvent eventInstance, CancellationToken cancellationToken = default)

    Inherits documentation from base type or interface.

    eventInstance: TEvent
    cancellationToken: CancellationToken

    Exceptions: ArgumentNullException: `eventInstance` is `null`

EricksonLopez.Outbox.MassTransit#

2
class

InboxIdempotencyFilter<T>

Ensamblado: EricksonLopez.Outbox.MassTransit
public sealed class InboxIdempotencyFilter<T> : IFilter<ConsumeContext<T>> where T : class
Implementa: IFilter<ConsumeContext<T>>

Provides a MassTransit filter that enforces the Inbox idempotency pattern by detecting and suppressing duplicate messages before they reach the business consumer.

Notas:

Type parameters: T: The type of the message being consumed.

Miembros (2)

  • methodProbe
    public void Probe(ProbeContext context)

    Probes the filter to expose its configuration in the MassTransit topology graph.

    context: ProbeContext
    The probe context that inspects the filter pipeline.
  • methodSend
    public async Task Send(ConsumeContext<T> context, IPipe<ConsumeContext<T>> next)

    Inherits documentation from base type or interface.

    context: ConsumeContext<T>
    next: IPipe<ConsumeContext<T>>
class

MassTransitBrokerPublisher

Ensamblado: EricksonLopez.Outbox.MassTransit
public sealed class MassTransitBrokerPublisher : IBrokerPublisher
Implementa: IBrokerPublisher

Provides a broker publisher implementation that dispatches outbox messages to a message broker via MassTransit.

Notas:

This bridge allows using EricksonLopez.Outbox for extreme database performance while delegating complex routing and topologies to MassTransit.

Miembros (4)

  • constructorMassTransitBrokerPublisher
    public MassTransitBrokerPublisher(IPublishEndpoint publishEndpoint)

    Initializes a new instance of the `MassTransitBrokerPublisher` class.

    publishEndpoint: IPublishEndpoint
    The MassTransit endpoint that publishes messages.

    Exceptions: ArgumentNullException: `publishEndpoint` is `null`

  • methodPublishAsync<T>
    public async ValueTask<DispatchResult> PublishAsync<T>(MessageEnvelope<T> message, DispatchContext context) where T : notnull

    Inherits documentation from base type or interface.

    message: MessageEnvelope<T>
    context: DispatchContext

    Propagates the correlation ID from `OutboxMessageMetadata` and any custom headers to the MassTransit publish context.

  • methodPublishBatchAsync<T>
    public async ValueTask<IReadOnlyList<DispatchResult>> PublishBatchAsync<T>(IReadOnlyList<MessageEnvelope<T>> messages, DispatchContext context) where T : notnull

    Inherits documentation from base type or interface.

    messages: IReadOnlyList<MessageEnvelope<T>>
    context: DispatchContext

    Delegates to `PublishAsync<T>` for each message in the batch sequentially.

  • methodPublishRawAsync
    public async ValueTask<DispatchResult> PublishRawAsync(OutboxMessage message, OutboxMessageMetadata metadata, DispatchContext context)

    Publishes a raw serialized outbox message as-is.

    message: OutboxMessage
    The raw outbox message to publish.
    metadata: OutboxMessageMetadata
    The metadata associated with the message.
    context: DispatchContext
    The context governing the dispatch operation, including cancellation tokens.

    Retorna: A task that represents the asynchronous dispatch operation, containing the `DispatchResult`.

    MassTransit does not natively support raw byte publishing without a known CLR type. This implementation publishes a `Dictionary<TKey, TValue>` envelope with the UTF-8 decoded payload and message type, relying on the `outbox.message_type` header for consumer routing.

EricksonLopez.Outbox.MediatR#

2
class

OutboxMediatRServiceCollectionExtensions

Ensamblado: EricksonLopez.Outbox.MediatR
public static class OutboxMediatRServiceCollectionExtensions

Provides extension methods for configuring the MediatR outbox publisher integration.

Miembros (1)

  • methodAddOutboxMediatRPublisher
    public static IServiceCollection AddOutboxMediatRPublisher(this IServiceCollection services)

    Registers the `OutboxNotificationPublisher` as the primary MediatR notification publisher.

    services: this IServiceCollection
    The service collection.

    Retorna: The modified service collection.

    Exceptions: ArgumentNullException: `services` is `null`

class

OutboxNotificationPublisher

Ensamblado: EricksonLopez.Outbox.MediatR
public sealed class OutboxNotificationPublisher : INotificationPublisher
Implementa: INotificationPublisher

Provides a MediatR `INotificationPublisher` implementation that seamlessly routes notifications to the transactional outbox (`IOutbox`) when active, while dispatching to in-process handlers.

Miembros (2)

  • constructorOutboxNotificationPublisher
    public OutboxNotificationPublisher(IOutbox outbox, IOutboxTransactionContext? transactionContext = null)

    Initializes a new instance of the `OutboxNotificationPublisher` class.

    outbox: IOutbox
    The outbox instance used to persist integration messages.
    transactionContext: IOutboxTransactionContext?
    The optional active transaction context.

    Exceptions: ArgumentNullException: `outbox` is `null`

  • methodPublish
    public async Task Publish(IEnumerable<NotificationHandlerExecutor> handlerExecutors, INotification notification, CancellationToken cancellationToken)

    Inherits documentation from base type or interface.

    handlerExecutors: IEnumerable<NotificationHandlerExecutor>
    notification: INotification
    cancellationToken: CancellationToken

EricksonLopez.Outbox.Mediator#

2
class

OutboxMediatorServiceCollectionExtensions

Ensamblado: EricksonLopez.Outbox.Mediator
public static class OutboxMediatorServiceCollectionExtensions

Provides extension methods for registering outbox mediator handlers with dependency injection.

Miembros (1)

  • methodAddOutboxNotificationHandler<TNotification>
    public static IServiceCollection AddOutboxNotificationHandler<TNotification>(this IServiceCollection services) where TNotification : INotification

    Registers an outbox notification handler for the specified `TNotification` type.

    services: this IServiceCollection
    The service collection.

    Retorna: The service collection for chaining.

    Type parameters: TNotification: The notification type. Exceptions: ArgumentNullException: `services` is `null`

class

OutboxNotificationHandler<TNotification>

Ensamblado: EricksonLopez.Outbox.Mediator
public sealed class OutboxNotificationHandler<TNotification> : INotificationHandler<TNotification> where TNotification : INotification
Implementa: INotificationHandler<TNotification>

Provides a mediator notification handler that routes notifications marked with `OutboxMessageAttribute` to the transactional outbox (`IOutbox`).

Notas:

Type parameters: TNotification: The notification type.

Miembros (2)

  • constructorOutboxNotificationHandler
    public OutboxNotificationHandler(IOutbox outbox, IOutboxTransactionContext? transactionContext = null)

    Initializes a new instance of the `OutboxNotificationHandler<TNotification>` class.

    outbox: IOutbox
    The outbox instance used to persist messages.
    transactionContext: IOutboxTransactionContext?
    The optional active transaction context.

    Exceptions: ArgumentNullException: `outbox` is `null`

  • methodHandle
    public async ValueTask Handle(TNotification notification, CancellationToken cancellationToken)

    Inherits documentation from base type or interface.

    notification: TNotification
    cancellationToken: CancellationToken

EricksonLopez.Outbox.MultiTenancy#

3
class

AmbientOutboxDispatchContextAccessor

Ensamblado: EricksonLopez.Outbox
public sealed class AmbientOutboxDispatchContextAccessor : IOutboxDispatchContextAccessor
Implementa: IOutboxDispatchContextAccessor

Thread-safe `AsyncLocal<T>` implementation of `IOutboxDispatchContextAccessor` exposing rehydrated `(TenantId, CompanyId, ExecutionPlane)` per dispatched message.

Miembros (2)

  • methodBeginScope
    public IDisposable BeginScope(OutboxDispatchTenantContext context)

    Establishes an ambient `OutboxDispatchTenantContext` scope for the current asynchronous flow.

    context: OutboxDispatchTenantContext
    The rehydrated dispatch tenant context.

    Retorna: An `IDisposable` token that restores the previous context on disposal.

  • propertyCurrent
    public OutboxDispatchTenantContext? Current { get; }

    Gets the ambient dispatch tenant context for the currently executing outbox message, or `null` outside dispatch.

interface

ITenantBrokerRouter

Ensamblado: EricksonLopez.Outbox
public interface ITenantBrokerRouter

Defines a contract for tenant-aware destination broker and topic or queue routing.

Miembros (1)

  • methodResolveDestination
    string ResolveDestination(string? tenantId, string baseDestination, string messageType)

    Determines the destination topic or queue name for a message belonging to a specific tenant.

    tenantId: string?
    The tenant identifier.
    baseDestination: string
    The standard or configured base topic/queue name.
    messageType: string
    The message type alias.

    Retorna: The tenant-specific routing destination.

interface

ITenantConnectionResolver

Ensamblado: EricksonLopez.Outbox
public interface ITenantConnectionResolver

Defines a contract for resolving tenant-specific database connection strings or schemas for partitioned multi-tenancy.

Miembros (1)

  • methodResolveConnectionStringAsync
    ValueTask<string> ResolveConnectionStringAsync(string tenantId, CancellationToken cancellationToken = default)

    Resolves the database connection string or schema identifier for the given tenant.

    tenantId: string
    The tenant identifier.
    cancellationToken: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: A task that represents the asynchronous resolution, returning the tenant connection string or target identifier.

EricksonLopez.Outbox.NServiceBus#

3
class

NServiceBusOutboxExtensions

Ensamblado: EricksonLopez.Outbox.NServiceBus
public static class NServiceBusOutboxExtensions

Provides extension methods for configuring the NServiceBus outbox integration.

Miembros (1)

  • methodEnableTransactionalOutbox
    public static EndpointConfiguration EnableTransactionalOutbox(this EndpointConfiguration endpointConfiguration)

    Enables the EricksonLopez.Outbox integration within the NServiceBus endpoint configuration.

    endpointConfiguration: this EndpointConfiguration
    The NServiceBus endpoint configuration.

    Retorna: The endpoint configuration for chaining.

    Exceptions: ArgumentNullException: `endpointConfiguration` is `null`

class

NServiceBusOutboxFeature

Ensamblado: EricksonLopez.Outbox.NServiceBus
public sealed class NServiceBusOutboxFeature : Feature
Hereda de: Feature

Provides an NServiceBus feature that registers the transactional outbox pipeline behavior.

Miembros (1)

  • constructorNServiceBusOutboxFeature
    public NServiceBusOutboxFeature()

    Initializes a new instance of the `NServiceBusOutboxFeature` class.

class

OutboxPublishBehavior

Ensamblado: EricksonLopez.Outbox.NServiceBus
public sealed class OutboxPublishBehavior : Behavior<IOutgoingLogicalMessageContext>
Hereda de: Behavior<IOutgoingLogicalMessageContext>

Provides an NServiceBus pipeline behavior that captures outgoing published and sent messages and routes them through the transactional outbox (`IOutbox`).

Miembros (2)

  • constructorOutboxPublishBehavior
    public OutboxPublishBehavior(IOutbox outbox)

    Initializes a new instance of the `OutboxPublishBehavior` class.

    outbox: IOutbox
    The outbox instance used to persist messages.

    Exceptions: ArgumentNullException: `outbox` is `null`

  • methodInvoke
    public override async Task Invoke(IOutgoingLogicalMessageContext context, Func<Task> next)

    Inherits documentation from base type or interface.

    context: IOutgoingLogicalMessageContext
    next: Func<Task>

EricksonLopez.Outbox.OpenTelemetry#

1
class

OutboxW3CTracePropagator

Ensamblado: EricksonLopez.Outbox.OpenTelemetry
public static class OutboxW3CTracePropagator

Propagates W3C TraceContext (`traceparent`, `tracestate`) and `baggage` headers across asynchronous Outbox storage and consumer boundaries while returning caller-owned `Activity` spans so spans are stopped and disposed deterministically without memory or `Activity.Current` leaks.

Miembros (6)

  • methodInjectTraceHeaders
    public static void InjectTraceHeaders(IDictionary<string, string> headers, Activity? activity = null)

    Injects the ambient `Activity.Current` W3C `traceparent`, `tracestate`, and `baggage` values into `headers` when a W3C activity is active.

    headers: IDictionary<string, string>
    Mutable message header dictionary.
    activity: Activity?
    Optional explicit activity; defaults to `Activity.Current`.
  • methodStartConsumerActivity
    public static Activity? StartConsumerActivity(string messageType, string messageId, IReadOnlyDictionary<string, string>? headers = null, string? correlationId = null, string? brokerSystemName = null)

    Starts a caller-owned `ActivityKind.Consumer` span linked to the W3C trace headers in `headers`. Callers MUST wrap the returned `Activity` in a `using` statement so `Activity.Dispose()` stops the span cleanly.

    messageType: string
    Destination/event type name.
    messageId: string
    Unique outbox/inbox message identifier.
    headers: IReadOnlyDictionary<string, string>?
    Optional serialized message headers containing `traceparent`.
    correlationId: string?
    Optional conversation correlation identifier.
    brokerSystemName: string?
    Broker system name (defaults to `"outbox"`).

    Retorna: A started `Activity` owned by the caller, or `null` when no listener is sampling.

  • methodTryExtractTraceContext
    public static bool TryExtractTraceContext(IReadOnlyDictionary<string, string>? headers, out ActivityContext parentContext, out IReadOnlyList<KeyValuePair<string, string?>> baggage)

    Attempts to parse a W3C `ActivityContext` and optional baggage items from `headers`.

    headers: IReadOnlyDictionary<string, string>?
    Read-only message header dictionary.
    parentContext: out ActivityContext
    When successful, receives the parsed `ActivityContext`.
    baggage: out IReadOnlyList<KeyValuePair<string, string?>>
    Receives any parsed W3C baggage key-value pairs.

    Retorna: `true` when a valid `traceparent` header was parsed; otherwise, `false`.

  • fieldBaggageHeader
    public const string BaggageHeader

    Canonical W3C baggage header key.

  • fieldTraceParentHeader
    public const string TraceParentHeader

    Canonical W3C traceparent header key.

  • fieldTraceStateHeader
    public const string TraceStateHeader

    Canonical W3C tracestate header key.

EricksonLopez.Outbox.Persistence#

17
class

AmbientOutboxTransactionContextAccessor

Ensamblado: EricksonLopez.Outbox
public sealed class AmbientOutboxTransactionContextAccessor : IOutboxTransactionContextAccessor
Implementa: IOutboxTransactionContextAccessor

Thread-safe `AsyncLocal<T>` implementation of `IOutboxTransactionContextAccessor` for propagating active pre-commit database transactions across asynchronous flows.

Miembros (3)

  • methodBeginScope
    public IDisposable BeginScope(DbConnection connection, DbTransaction transaction)

    Pushes an active `DbConnection` and `DbTransaction` onto the ambient asynchronous flow and restores the prior context on disposal.

    connection: DbConnection
    The open database connection.
    transaction: DbTransaction
    The active uncommitted database transaction.

    Retorna: An `IDisposable` scope handle.

  • methodBeginScope
    public IDisposable BeginScope(IOutboxTransactionContext context)

    Pushes an active `IOutboxTransactionContext` onto the ambient asynchronous flow and restores the prior context on disposal.

    context: IOutboxTransactionContext
    The active transaction context.

    Retorna: An `IDisposable` scope handle.

  • propertyCurrent
    public IOutboxTransactionContext? Current { get; }

    Gets the ambient active transaction context for the current asynchronous execution flow, or `null` if none is active.

class

DbTransactionContext

Ensamblado: EricksonLopez.Outbox.Abstractions
public sealed class DbTransactionContext : IRelationalOutboxTransactionContext
Implementa: IRelationalOutboxTransactionContext

Represents an ADO.NET database transaction implementation of `IRelationalOutboxTransactionContext`.

Miembros (5)

  • constructorDbTransactionContext
    public DbTransactionContext(DbTransaction dbTransaction)
    dbTransaction: DbTransaction

    Exceptions: System.ArgumentNullException: `dbTransaction` is `null`

  • propertyConnection
    public object? Connection { get; }

    Inherits documentation from base type or interface.

  • propertyDbConnection
    public DbConnection? DbConnection { get; }

    Gets the strongly typed `DbConnection` associated with this context, or `null` if none is available.

  • propertyDbTransaction
    public DbTransaction? DbTransaction { get; }

    Gets the strongly typed `DbTransaction` associated with this context, or `null` if none is active.

  • propertyTransaction
    public object Transaction { get; }

    Inherits documentation from base type or interface.

interface

IDeadLetterRepository

Ensamblado: EricksonLopez.Outbox
public interface IDeadLetterRepository

Defines a contract for dead-letter queue storage operations.

Notas:

A message is dead-lettered when it has exhausted all configured retry attempts without being successfully dispatched to the broker. Dead-lettered messages are stored separately from the main outbox table to: 1. Prevent them from being re-fetched by the dispatcher indefinitely. 2. Allow human inspection, manual replay, or automated discard. 3. Provide a durable audit trail of permanently failed messages. Implementations must guarantee: - Atomic insert within the caller's transaction (or a separate connection). - The original OutboxMessage ID is preserved in OriginalMessageId for correlation. - Graceful handling of transaction=default. The dispatcher frequently attempts to insert dead letters outside of a transaction context. If transaction is null, the repository MUST open its own connection and auto-commit the insert.

Miembros (5)

  • methodDeleteAsync
    ValueTask DeleteAsync(Guid id, CancellationToken cancellationToken = default)

    Deletes a dead-lettered message by its unique identifier.

    id: Guid
    The unique identifier of the dead-lettered message to delete.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • methodGetAsync
    ValueTask<IReadOnlyList<DeadLetterMessage>> GetAsync(int limit = 100, DateTimeOffset? after = null, CancellationToken cancellationToken = default)

    Retrieves a page of dead-lettered messages for inspection or replay.

    limit: int
    The maximum number of records to return.
    after: DateTimeOffset?
    The cursor indicating to return records dead-lettered after this timestamp. Pass `DateTimeOffset.MinValue` for the first page.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the retrieved page of dead-lettered messages.

  • methodInsertAsync
    ValueTask InsertAsync(DeadLetterMessage message, EricksonLopez.Outbox.Persistence.IOutboxTransactionContext? transaction = default, CancellationToken cancellationToken = default)

    Persists a dead-lettered message.

    message: DeadLetterMessage
    The dead-lettered message to persist.
    transaction: EricksonLopez.Outbox.Persistence.IOutboxTransactionContext?
    The optional transaction context. If `null`, the repository must open its own connection and auto-commit the insert.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Called by the Dispatcher after a message has exhausted its `Retry.RetryPolicy`.

  • methodPurgeAsync
    ValueTask PurgeAsync(DateTimeOffset olderThan, CancellationToken cancellationToken = default)

    Purges all dead-lettered messages older than the specified timestamp.

    olderThan: DateTimeOffset
    The timestamp threshold; messages older than this value will be purged.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • propertyIsFirstPartyImplementation
    bool IsFirstPartyImplementation { get; }

    Gets a value indicating whether this is a first-party (built-in) implementation.

    Used by `OutboxStartupValidator` to warn operators when a third-party `IDeadLetterRepository` is registered, reminding them to verify that their implementation correctly handles `transaction = null` (auto-commit mode). All first-party storage engine implementations override this to return `true`. Third-party implementations that do not override this will return `false`, triggering the startup advisory log message. This is a Zero-Reflection pattern: no `GetType().Name`, no string comparisons, no assembly scanning. The check is a simple virtual dispatch.

interface

IIdempotencyRepository

Ensamblado: EricksonLopez.Outbox.Abstractions
public interface IIdempotencyRepository

Defines the persistence abstraction for storing, querying, and purging idempotency records.

Notas:

Implementations must guarantee atomic insert-or-ignore semantics.

Miembros (2)

  • methodPurgeExpiredRecordsAsync
    ValueTask PurgeExpiredRecordsAsync(DateTimeOffset olderThan, CancellationToken cancellationToken = default)

    Purges idempotency records older than the specified timestamp.

    olderThan: DateTimeOffset
    The timestamp threshold; records older than this value will be purged.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Called periodically by `InboxCleanupService` to prevent table bloat.

  • methodTryInsertAsync
    ValueTask<bool> TryInsertAsync(IdempotencyRecord record, IOutboxTransactionContext? transaction = default, CancellationToken cancellationToken = default)

    Attempts to insert an idempotency record.

    record: IdempotencyRecord
    The idempotency record to insert.
    transaction: IOutboxTransactionContext?
    The optional transaction context.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result is `true` if the record was inserted; otherwise, `false` if the record already exists (duplicate).

interface

IOutboxPreCommitFlusher

Ensamblado: EricksonLopez.Outbox.Abstractions
public interface IOutboxPreCommitFlusher

Flushes messages buffered in the scoped `IOutboxCollector` into the outbox database table inside the active `DbTransaction` strictly before `CommitAsync` executes.

Miembros (2)

  • methodFlushBeforeCommitAsync
    ValueTask<int> FlushBeforeCommitAsync(DbConnection connection, DbTransaction transaction, CancellationToken cancellationToken = default)

    Persists all pending messages staged in the current scope into the active `connection` and `transaction` before commit.

    connection: DbConnection
    The open database connection.
    transaction: DbTransaction
    The active uncommitted database transaction.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: The number of outbox messages persisted in the batch.

  • methodFlushBeforeCommitAsync
    ValueTask<int> FlushBeforeCommitAsync(IOutboxTransactionContext transaction, CancellationToken cancellationToken = default)

    Persists all pending messages staged in the current scope into the active `transaction` before commit.

    transaction: IOutboxTransactionContext
    The active relational transaction context.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: The number of outbox messages persisted in the batch.

interface

IOutboxRepository

Ensamblado: EricksonLopez.Outbox
public interface IOutboxRepository

Defines a contract for outbox pattern storage operations.

Notas:

Ordering Guarantees: Within a single dispatcher instance, messages are fetched in `ORDER BY created_at ASC, id ASC` order and processed by parallel consumer tasks. This provides FIFO ordering within each consumer task, but no global ordering when `MaxDegreeOfParallelism > 1`. With multiple dispatcher instances (horizontal scaling), `SKIP LOCKED` ensures each instance claims a non-overlapping subset of messages, resulting in non-deterministic global ordering. For strict FIFO ordering, use a single dispatcher instance with `MaxDegreeOfParallelism = 1`. In partitioned table deployments, the ordering guarantee applies within each partition only. Cross-partition ordering is best-effort.

Miembros (10)

  • methodFetchPendingAsync
    ValueTask<IReadOnlyList<OutboxMessage>> FetchPendingAsync(int batchSize, CancellationToken cancellationToken = default)

    Retrieves a batch of pending messages ready for delivery.

    batchSize: int
    The maximum number of messages to retrieve.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the batch of messages retrieved.

    The method fetches up to the specified batch size of messages that are in the Pending state (0) and whose delivery time is less than or equal to the current UTC time. Implementations guarantee safe concurrent polling by using SKIP LOCKED or equivalent semantics, atomically transitioning the fetched messages to the InFlight state (1). Scheduling edge case — `deliver_at` vs `MaxMessageAge`: Messages stored with a future `deliver_at` timestamp that exceeds `MaxMessageAge` will be silently excluded from polling by the `created_at` age guard. Such messages will not be processed and will not be automatically dead-lettered. Ensure `OutboxRuntimeOptions.MaxMessageAge` is greater than the maximum `deliver_at` offset used in your application (e.g., if scheduling up to 7 days ahead, set `MaxMessageAge ≥ 8 days`). Ordering with multiple dispatcher instances: When multiple dispatcher instances run concurrently, messages are fetched in `ORDER BY created_at ASC, id ASC` order but can be claimed by different instances via `SKIP LOCKED`, resulting in non-deterministic global ordering. In partitioned table setups, the order guarantee applies within each partition only. For strict global ordering, use a single dispatcher instance with `MaxDegreeOfParallelism = 1`.

  • methodGetMessageAsync
    ValueTask<OutboxMessage?> GetMessageAsync(Guid id, CancellationToken cancellationToken = default)

    Retrieves a single outbox message by its unique identifier, regardless of its current state.

    id: Guid
    The unique identifier of the message to retrieve.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: The `OutboxMessage` with the specified `id`, or `null` if no message with that ID exists in the outbox table.

    AUDIT-FIX P1-G — Default Interface Method for operational tooling: Designed for debugging, manual requeue, and administrative UIs that need to inspect a specific message. It is not used in the normal dispatcher hot path. This is a Default Interface Method (DIM): existing implementations automatically inherit the default implementation which throws `NotSupportedException`. Storage engine implementations should override `GetMessageAsync(Guid, CancellationToken)` for efficient single-row lookup. For PostgreSQL, the expected implementation is: `SELECT * FROM outbox.messages WHERE id = @Id LIMIT 1;`

  • methodGetMessageAsync
    ValueTask<OutboxMessage?> GetMessageAsync(Guid id, DateTimeOffset? createdAtHint, CancellationToken cancellationToken = default)

    Retrieves a single outbox message by its unique identifier, with an optional `created_at` hint to enable partition pruning in range-partitioned table deployments.

    id: Guid
    The unique identifier of the message to retrieve.
    createdAtHint: DateTimeOffset?
    An optional `DateTimeOffset` hint that, when provided, enables partition pruning in range-partitioned table deployments. Must match the exact `created_at` value stored for the message. Pass `null` to fall back to a full-table scan.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: The `OutboxMessage` with the specified `id`, or `null` if no message with that ID exists in the outbox table.

    S-01 AUDIT FIX — Partition pruning hint: In range-partitioned deployments (e.g., PostgreSQL with PARTITION BY RANGE on `created_at`), a lookup by `id` alone requires scanning all partition children because `id` is not the partition key. Providing `createdAtHint` adds an additional `AND created_at = @CreatedAt` predicate, allowing the PostgreSQL query planner to prune to the single target partition and perform an index seek instead of a full-table scan. When to use: Administrative UIs and operational tools that already have the full `OutboxMessage.CreatedAt` value (e.g., from a previous list query or from the original `StoreAsync` response) should use this overload for significantly faster lookup. Default implementation: Delegates to `GetMessageAsync(Guid, CancellationToken)` (ignoring the hint) for backward compatibility. Partition-aware storage engines should override `GetMessageAsync(Guid, DateTimeOffset?, CancellationToken)` to enable partition pruning.

  • methodGetPendingCountAsync
    ValueTask<long> GetPendingCountAsync(CancellationToken cancellationToken = default)

    Retrieves the approximate count of messages awaiting processing.

    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the approximate pending message count.

    Includes messages in the Pending (0) or Failed (3) states for metrics and monitoring.

  • methodInsertAsync
    ValueTask InsertAsync(OutboxMessage record, IOutboxTransactionContext transaction, CancellationToken cancellationToken = default)

    Inserts a single message into the outbox table atomically within the specified transaction.

    record: OutboxMessage
    The message to insert into the outbox.
    transaction: IOutboxTransactionContext
    The context representing the active database transaction.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • methodInsertBatchAsync
    ValueTask InsertBatchAsync(ReadOnlyMemory<OutboxMessage> records, IOutboxTransactionContext transaction, CancellationToken cancellationToken = default)

    Inserts a batch of messages into the outbox table in a single round-trip.

    records: ReadOnlyMemory<OutboxMessage>
    The batch of messages to insert.
    transaction: IOutboxTransactionContext
    The context representing the active database transaction.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Implementations should use bulk insert mechanisms (e.g., COPY, UNNEST, or table-valued parameters). If native bulk insert is unavailable, implementations fall back to individual inserts.

  • methodMarkAsDispatchedAsync
    ValueTask MarkAsDispatchedAsync(IReadOnlyList<OutboxMessage> messages, CancellationToken cancellationToken = default)

    Atomically marks the specified messages as successfully dispatched.

    messages: IReadOnlyList<OutboxMessage>
    The collection of messages to mark as dispatched.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • methodMarkAsFailedAsync
    ValueTask MarkAsFailedAsync(IReadOnlyList<OutboxMessage> messages, string error, bool isDeadLetter = false, CancellationToken cancellationToken = default)

    Marks the specified messages as failed, updating their error details and retry counts.

    messages: IReadOnlyList<OutboxMessage>
    The collection of messages that failed to process.
    error: string
    The error message or exception details causing the failure.
    isDeadLetter: bool
    `true` to mark the messages as permanently failed (dead letter); otherwise, `false`.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Is typically invoked by `Retry.RetryDispatcherInterceptor` when publishing fails. If the maximum retry attempts are exhausted, the message may be marked as a dead letter. Security Warning: The `error` parameter may contain sensitive information (such as connection strings in stack traces). Ensure exceptions are sanitized in production environments before they are persisted, to prevent leaking sensitive data.

  • methodPurgeDispatchedMessagesAsync
    ValueTask<int> PurgeDispatchedMessagesAsync(DateTimeOffset cutoff, int batchSize = 1000, CancellationToken cancellationToken = default)

    Purges dispatched messages that were processed prior to the specified cutoff timestamp. Used by `Hosting.OutboxCleanupService` when `DeleteOnDispatch = false`.

    cutoff: DateTimeOffset
    The cutoff timestamp; messages dispatched prior to this time will be deleted.
    batchSize: int
    The maximum number of rows to delete in a single batch.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation, returning the number of purged rows.

  • methodReclaimStaleMessagesAsync
    ValueTask<int> ReclaimStaleMessagesAsync(TimeSpan staleTimeout, CancellationToken cancellationToken = default)

    Reclaims messages that have remained in the InFlight state longer than the specified timeout.

    staleTimeout: TimeSpan
    The duration after which an InFlight message is considered abandoned.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the number of messages reclaimed.

    This mechanism prevents message loss if a dispatcher crashes after claiming a batch (transitioning from state 0 to 1) but before marking it as dispatched. Implementations must atomically reset these messages to the Pending state (0) if their last updated time is older than the current UTC time minus the stale timeout.

interface

IOutboxTransactionContext

Ensamblado: EricksonLopez.Outbox.Abstractions
public interface IOutboxTransactionContext

Defines a generic transaction context for the Outbox, decoupling operations from specific database transaction types.

Miembros (3)

  • methodGetContext<T>
    T? GetContext<T>() where T : class

    Returns the underlying transaction cast to `T`, or `null` if the cast fails.

    Retorna: The transaction cast to `T`, or `null` if the cast is not valid.

    Type parameters: T: The target transaction type to cast to.

  • propertyConnection
    object? Connection { get; }

    Gets the underlying connection object, or `null` if no connection is associated.

  • propertyTransaction
    object Transaction { get; }

    Gets the underlying transaction object as an untyped reference.

interface

IOutboxTransactionContextAccessor

Ensamblado: EricksonLopez.Outbox.Abstractions
public interface IOutboxTransactionContextAccessor

Provides ambient `AsyncLocal` access to the active uncommitted `IOutboxTransactionContext` during pre-commit domain event and command execution.

Miembros (3)

  • methodBeginScope
    IDisposable BeginScope(DbConnection connection, DbTransaction transaction)

    Pushes an active `DbConnection` and `DbTransaction` onto the ambient asynchronous flow and restores the prior context on disposal.

    connection: DbConnection
    The open database connection.
    transaction: DbTransaction
    The active uncommitted database transaction.

    Retorna: An `IDisposable` scope handle.

  • methodBeginScope
    IDisposable BeginScope(IOutboxTransactionContext context)

    Pushes an active `IOutboxTransactionContext` onto the ambient asynchronous flow and restores the prior context on disposal.

    context: IOutboxTransactionContext
    The active transaction context.

    Retorna: An `IDisposable` scope handle.

  • propertyCurrent
    IOutboxTransactionContext? Current { get; }

    Gets the ambient active transaction context for the current asynchronous execution flow, or `null` if none is active.

interface

IOutboxTransactionContext<TConnection, TTransaction>

Ensamblado: EricksonLopez.Outbox.Abstractions
public interface IOutboxTransactionContext<TConnection, TTransaction> : IOutboxTransactionContext
Implementa: IOutboxTransactionContext

Defines a strongly typed transaction context abstraction supporting relational and non-relational database transaction primitives.

Notas:

Type parameters: TConnection: The underlying connection or client type.; TTransaction: The underlying transaction or session type.

Miembros (2)

  • propertyConnection
    new TConnection? Connection { get; }

    Gets the strongly typed underlying connection or database client.

  • propertyTransaction
    new TTransaction? Transaction { get; }

    Gets the strongly typed underlying active transaction or session.

interface

IRelationalOutboxTransactionContext

Ensamblado: EricksonLopez.Outbox.Abstractions
public interface IRelationalOutboxTransactionContext : IOutboxTransactionContext
Implementa: IOutboxTransactionContext

Defines a specialized transaction context for relational ADO.NET databases.

Miembros (2)

  • propertyDbConnection
    DbConnection? DbConnection { get; }

    Gets the strongly typed `DbConnection` associated with this context, or `null` if none is available.

  • propertyDbTransaction
    DbTransaction? DbTransaction { get; }

    Gets the strongly typed `DbTransaction` associated with this context, or `null` if none is active.

class

OutboxGenericTransactionContextExtensions

Ensamblado: EricksonLopez.Outbox
public static class OutboxGenericTransactionContextExtensions

Convenience extension methods for creating strongly-typed `IOutboxTransactionContext<TConnection, TTransaction>` instances.

Miembros (1)

  • methodToOutboxContext<TConnection, TTransaction>
    public static IOutboxTransactionContext<TConnection, TTransaction> ToOutboxContext<TConnection, TTransaction>(this TTransaction transaction, TConnection? connection = default)

    Wraps a transaction and optional connection in a strongly typed `IOutboxTransactionContext<TConnection, TTransaction>`.

    transaction: this TTransaction
    The active transaction or session instance.
    connection: TConnection?
    The optional connection or client instance.

    Retorna: An instance of `IOutboxTransactionContext<TConnection, TTransaction>`.

    Type parameters: TConnection: The type of the connection.; TTransaction: The type of the transaction.

class

OutboxRepositoryExtensions

Ensamblado: EricksonLopez.Outbox
public static class OutboxRepositoryExtensions

Provides extension methods for `IOutboxRepository`.

Miembros (1)

  • methodMarkAsFailedAsync
    public static ValueTask MarkAsFailedAsync(this IOutboxRepository repository, OutboxMessage message, string error, bool isDeadLetter = false, CancellationToken cancellationToken = default)

    Marks a single message as failed.

    repository: this IOutboxRepository
    The outbox repository to update.
    message: OutboxMessage
    The message that failed to process.
    error: string
    The error message or exception details describing the failure.
    isDeadLetter: bool
    `true` to mark the message as permanently failed (dead letter); otherwise, `false`.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

class

OutboxTransactionContext

Ensamblado: EricksonLopez.Outbox
public sealed class OutboxTransactionContext : IOutboxTransactionContext
Implementa: IOutboxTransactionContext

Provides a non-generic implementation of `IOutboxTransactionContext` for untyped transactions.

Miembros (3)

  • constructorOutboxTransactionContext
    public OutboxTransactionContext(object connection, object transaction)

    Initializes a new instance of the `OutboxTransactionContext` class.

    connection: object
    The generic connection object.
    transaction: object
    The generic transaction object.

    Exceptions: ArgumentNullException: `connection` or `transaction` is `null`

  • propertyConnection
    public object Connection { get; }

    Gets the underlying connection object, or `null` if no connection is associated.

  • propertyTransaction
    public object Transaction { get; }

    Gets the underlying transaction object as an untyped reference.

class

OutboxTransactionContextExtensions

Ensamblado: EricksonLopez.Outbox.Abstractions
public static class OutboxTransactionContextExtensions

Convenience extension methods for creating `IOutboxTransactionContext` instances.

Miembros (1)

  • methodToOutboxContext
    public static IOutboxTransactionContext ToOutboxContext(this DbTransaction transaction)

    Wraps the specified `DbTransaction` in an `IOutboxTransactionContext`.

    transaction: this DbTransaction
    The ADO.NET database transaction.

    Retorna: An `IOutboxTransactionContext` wrapping the transaction.

    Exceptions: ArgumentNullException: `transaction` is `null`

class

OutboxTransactionContext<TConnection, TTransaction>

Ensamblado: EricksonLopez.Outbox
public sealed class OutboxTransactionContext<TConnection, TTransaction> : IOutboxTransactionContext<TConnection, TTransaction>
Implementa: IOutboxTransactionContext<TConnection, TTransaction>

Provides a strongly-typed implementation of `IOutboxTransactionContext<TConnection, TTransaction>` for relational and non-relational database transaction primitives.

Notas:

Type parameters: TConnection: The underlying connection or client type.; TTransaction: The underlying transaction or session type.

Miembros (3)

  • constructorOutboxTransactionContext
    public OutboxTransactionContext(TConnection? connection, TTransaction transaction)

    Initializes a new instance of the `OutboxTransactionContext<TConnection, TTransaction>` class.

    connection: TConnection?
    The underlying connection or database client.
    transaction: TTransaction
    The underlying active transaction or session.

    Exceptions: ArgumentNullException: `transaction` is `null`

  • propertyConnection
    public TConnection? Connection { get; }

    Gets the underlying connection object, or `null` if no connection is associated.

  • propertyTransaction
    public TTransaction? Transaction { get; }

    Gets the underlying transaction object as an untyped reference.

class

ScopedOutboxCollector

Ensamblado: EricksonLopez.Outbox
public sealed class ScopedOutboxCollector : IOutboxCollector, IOutboxPreCommitFlusher
Implementa: IOutboxCollector, IOutboxPreCommitFlusher

Scoped pre-commit outbox collector and flusher that stages strongly-typed integration messages in-memory without reflection and persists them atomically inside the active `DbTransaction` prior to `CommitAsync`.

Miembros (6)

  • constructorScopedOutboxCollector
    public ScopedOutboxCollector(IOutboxRepository repository, IOutboxSerializer serializer, IOutboxMessageTypeResolver typeResolver, IOptions<OutboxRuntimeOptions> options, OutboxMetrics metrics, TimeProvider? timeProvider = null)

    Initializes a new instance of the `ScopedOutboxCollector` class.

    repository: IOutboxRepository
    serializer: IOutboxSerializer
    typeResolver: IOutboxMessageTypeResolver
    options: IOptions<OutboxRuntimeOptions>
    metrics: OutboxMetrics
    timeProvider: TimeProvider?
  • methodClear
    public void Clear()

    Discards all buffered messages (invoked upon transaction rollback or exception).

  • methodEnqueue<TMessage>
    public void Enqueue<TMessage>(TMessage message, OutboxMessageMetadata metadata = default, DateTimeOffset? deliverAt = null) where TMessage : notnull

    Stages a strongly-typed integration message for pre-commit transactional persistence.

    message: TMessage
    The non-null message payload.
    metadata: OutboxMessageMetadata
    Optional correlation, causation, tenant, company, and custom headers.
    deliverAt: DateTimeOffset?
    Optional scheduled UTC delivery timestamp.

    Type parameters: TMessage: The concrete integration message type (serialized without runtime reflection).

  • methodFlushBeforeCommitAsync
    public ValueTask<int> FlushBeforeCommitAsync(DbConnection connection, DbTransaction transaction, CancellationToken cancellationToken = default)

    Persists all pending messages staged in the current scope into the active `connection` and `transaction` before commit.

    connection: DbConnection
    The open database connection.
    transaction: DbTransaction
    The active uncommitted database transaction.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: The number of outbox messages persisted in the batch.

  • methodFlushBeforeCommitAsync
    public async ValueTask<int> FlushBeforeCommitAsync(IOutboxTransactionContext transaction, CancellationToken cancellationToken = default)

    Persists all pending messages staged in the current scope into the active `transaction` before commit.

    transaction: IOutboxTransactionContext
    The active relational transaction context.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: The number of outbox messages persisted in the batch.

  • propertyPendingCount
    public int PendingCount { get; }

    Gets the number of buffered messages currently awaiting pre-commit persistence.

struct

SingleOutboxMessageList.Enumerator

Ensamblado: EricksonLopez.Outbox
public struct Enumerator : IEnumerator<OutboxMessage>
Implementa: IEnumerator<OutboxMessage>

Enumerates a single `OutboxMessage` without heap allocations.

Miembros (5)

  • constructorEnumerator
    public Enumerator(OutboxMessage message)

    Initializes a new instance of the `Enumerator` struct for the specified outbox message.

    message: OutboxMessage
    The single outbox message to enumerate.
  • methodDispose
    public void Dispose()

    Inherits documentation from base type or interface.

  • methodMoveNext
    public bool MoveNext()

    Inherits documentation from base type or interface.

  • methodReset
    public void Reset()

    Inherits documentation from base type or interface.

  • propertyCurrent
    public OutboxMessage Current { get; }

    Inherits documentation from base type or interface.

EricksonLopez.Outbox.Pipeline#

3
interface

IOutboxMiddleware

Ensamblado: EricksonLopez.Outbox
public interface IOutboxMiddleware

Defines a middleware component that participates in the outbox dispatch pipeline.

Miembros (1)

  • methodInvokeAsync
    ValueTask<DispatchResult> InvokeAsync(OutboxMessage message, OutboxMessageMetadata metadata, OutboxPipelineDelegate next, CancellationToken cancellationToken)

    Invokes the middleware logic for the given message.

    message: OutboxMessage
    The outbox message being processed.
    metadata: OutboxMessageMetadata
    The metadata associated with the outbox message.
    next: OutboxPipelineDelegate
    The next delegate in the pipeline chain.
    cancellationToken: CancellationToken
    A token that can be used to cancel the middleware execution.

    Retorna: A task representing the asynchronous operation, containing the `DispatchResult`.

class

OutboxPipeline

Ensamblado: EricksonLopez.Outbox
public sealed class OutboxPipeline

Builds and executes an immutable chain of `IOutboxMiddleware` components.

Miembros (2)

  • constructorOutboxPipeline
    public OutboxPipeline(IEnumerable<IOutboxMiddleware> middlewares, OutboxPipelineDelegate terminal)

    Initializes a new instance of the `OutboxPipeline` class.

    middlewares: IEnumerable<IOutboxMiddleware>
    The sequence of middleware components to include in the pipeline.
    terminal: OutboxPipelineDelegate
    The final delegate to execute at the end of the middleware chain.

    Exceptions: ArgumentNullException: `middlewares` or `terminal` is `null`

  • methodExecuteAsync
    public ValueTask<DispatchResult> ExecuteAsync(OutboxMessage message, OutboxMessageMetadata metadata, CancellationToken cancellationToken)

    Executes the pre-built, fully assembled middleware chain for the given message.

    message: OutboxMessage
    The outbox message to process through the pipeline.
    metadata: OutboxMessageMetadata
    The metadata associated with the outbox message.
    cancellationToken: CancellationToken
    A token that can be used to cancel the pipeline execution.

    Retorna: A task that represents the asynchronous pipeline execution, yielding the final `DispatchResult`.

delegate

OutboxPipelineDelegate

Ensamblado: EricksonLopez.Outbox
public delegate ValueTask<DispatchResult> OutboxPipelineDelegate(OutboxMessage message, OutboxMessageMetadata metadata, CancellationToken cancellationToken)
Hereda de: System.MulticastDelegate

Represents a single step in the outbox dispatch pipeline.

Miembros (0)

Este tipo declara 0 miembros públicos (por ejemplo, interfaz marcadora o enum/record vacío).

EricksonLopez.Outbox.RabbitMQ#

1
class

RabbitMQBrokerPublisher

Ensamblado: EricksonLopez.Outbox.Brokers.RabbitMQ
public sealed class RabbitMQBrokerPublisher : IBrokerPublisher
Implementa: IBrokerPublisher

Provides a broker publisher implementation that dispatches outbox messages to a RabbitMQ exchange using the asynchronous client.

Miembros (4)

  • constructorRabbitMQBrokerPublisher
    public RabbitMQBrokerPublisher(IChannel channel, IOutboxSerializer serializer, string exchangeName = "")

    Initializes a new instance of the `RabbitMQBrokerPublisher` class.

    channel: IChannel
    The RabbitMQ communication channel.
    serializer: IOutboxSerializer
    The serializer that encodes the message payload.
    exchangeName: string
    The target exchange name for publishing messages.

    Exceptions: ArgumentNullException: `channel` or `serializer` is `null`

  • methodPublishAsync<T>
    public async ValueTask<DispatchResult> PublishAsync<T>(MessageEnvelope<T> message, DispatchContext context) where T : notnull

    Inherits documentation from base type or interface.

    message: MessageEnvelope<T>
    context: DispatchContext
  • methodPublishBatchAsync<T>
    public async ValueTask<IReadOnlyList<DispatchResult>> PublishBatchAsync<T>(IReadOnlyList<MessageEnvelope<T>> messages, DispatchContext context) where T : notnull

    Inherits documentation from base type or interface.

    messages: IReadOnlyList<MessageEnvelope<T>>
    context: DispatchContext
  • methodPublishRawAsync
    public async ValueTask<DispatchResult> PublishRawAsync(OutboxMessage message, OutboxMessageMetadata metadata, DispatchContext context)

    Publishes a raw serialized outbox message as-is.

    message: OutboxMessage
    The raw outbox message to publish.
    metadata: OutboxMessageMetadata
    The metadata associated with the message.
    context: DispatchContext
    The context governing the dispatch operation, including cancellation tokens.

    Retorna: A task that represents the asynchronous dispatch operation, containing the `DispatchResult`.

    Used by the Dispatcher which works with pre-serialized payloads, avoiding runtime generics and reflection for NativeAOT compatibility. DispatchResult contract for implementers: **Scenario**: **Return value**: - **Message published successfully**: **`DispatchResult.Ok()`**: - **Transient / recoverable failure (network timeout, broker unreachable, rate-limited)**: **`DispatchResult.FailAndRetry(exception)`**: - **Fatal / unrecoverable failure (schema mismatch, serialization error, message too large for broker, authorization denied)**: **`DispatchResult.FailFatal(exception)`**: Do NOT throw exceptions here. Thrown exceptions are treated as fatal failures by the dispatcher (equivalent to `DispatchResult.FailFatal`). Always catch broker exceptions and map them to the appropriate `DispatchResult`. Do NOT return `default(DispatchResult)`. The default value of the struct (`Success=false, ShouldRetry=false, Error=null`) is an invalid state that will cause the dispatcher to dead-letter the message with a misleading "no error" state. Always use one of the factory methods: `DispatchResult.Ok()`, `DispatchResult.FailAndRetry(ex)`, or `DispatchResult.FailFatal(ex)`. The dispatcher wraps calls to the publisher with a retry interceptor, which automatically retries `FailAndRetry` results with exponential backoff. Returning `FailFatal` bypasses retry and dead-letters the message immediately. OpenTelemetry — `messaging.system` tag requirement: The outbox core sets `messaging.system = "outbox"` as a default on the dispatch Activity. Broker implementers MUST override this tag with the actual broker name: `System.Diagnostics.Activity.Current?.SetTag("messaging.system", "rabbitmq"); // or "kafka", "azure_service_bus", etc.` This is required by the OpenTelemetry Messaging Semantic Conventions (v1.26+): https://opentelemetry.io/docs/specs/semconv/messaging/messaging-spans/#messaging-attributes

EricksonLopez.Outbox.Rebus#

2
class

OutboxOutgoingStep

Ensamblado: EricksonLopez.Outbox.Rebus
public sealed class OutboxOutgoingStep : IOutgoingStep
Implementa: IOutgoingStep

Provides a Rebus outgoing pipeline step that captures messages and routes them through the transactional outbox (`IOutbox`).

Miembros (2)

  • constructorOutboxOutgoingStep
    public OutboxOutgoingStep(IOutbox outbox)

    Initializes a new instance of the `OutboxOutgoingStep` class.

    outbox: IOutbox
    The outbox instance.

    Exceptions: ArgumentNullException: `outbox` is `null`

  • methodProcess
    public async Task Process(OutgoingStepContext context, Func<Task> next)

    Inherits documentation from base type or interface.

    context: OutgoingStepContext
    next: Func<Task>
class

RebusOutboxConfigurationExtensions

Ensamblado: EricksonLopez.Outbox.Rebus
public static class RebusOutboxConfigurationExtensions

Provides configuration extension methods for integrating the outbox with Rebus.

Miembros (1)

  • methodEnableTransactionalOutbox
    public static void EnableTransactionalOutbox(this OptionsConfigurer configurer, IOutbox outbox)

    Configures Rebus pipeline to use the transactional outbox step.

    configurer: this OptionsConfigurer
    The options configurer.
    outbox: IOutbox
    The outbox instance.

    Exceptions: ArgumentNullException: `configurer` or `outbox` is `null`

EricksonLopez.Outbox.Retry#

10
class

CircuitBreakerOpenException

Ensamblado: EricksonLopez.Outbox
public sealed class CircuitBreakerOpenException : Exception
Hereda de: Exception

Thrown when a request is rejected because the `CircuitBreakerState` is in the Open state. This exception is used internally by `RetryDispatcherInterceptor` to signal that the broker is unreachable and the circuit breaker is preventing further attempts.

Notas:

This exception is never propagated to the caller. The `RetryDispatcherInterceptor` converts circuit-breaker rejections into `DispatchResult.FailAndRetry(ex, incrementRetryCount: false)`, which causes the message to remain in-flight and be reclaimed by the stale message reclaimer after the configured `ReclaimTimeout` \u2014 acting as a natural backoff without burning retry attempts.

Miembros (1)

  • constructorCircuitBreakerOpenException
    public CircuitBreakerOpenException(string message)

    Initializes a new instance of the `CircuitBreakerOpenException` class.

    message: string
    The message that describes the error.
class

CircuitBreakerState

Ensamblado: EricksonLopez.Outbox
public sealed class CircuitBreakerState

Tracks the circuit-breaker state for a single broker publisher, providing zero-allocation protection against overwhelming an unavailable broker.

Notas:

Implements a lightweight three-state machine (`CircuitState.Closed`, `CircuitState.Open`, `CircuitState.HalfOpen`) without introducing a dependency on Polly or similar libraries. Thread safety: All state mutations are protected by a single lock to ensure atomicity of composite state changes. The three fields (`_state`, `_failureCount`, `_openedAtTicks`) must always be updated as a unit.

Miembros (8)

  • constructorCircuitBreakerState
    public CircuitBreakerState(int failureThreshold = 5, TimeSpan? openDuration = null)

    Initializes a new instance of the `CircuitBreakerState` class.

    failureThreshold: int
    The number of consecutive failures before opening the circuit.
    openDuration: TimeSpan?
    The duration the circuit stays open. Defaults to 30 seconds.

    Exceptions: ArgumentOutOfRangeException: `failureThreshold` is less than or equal to 0

  • constructorCircuitBreakerState
    public CircuitBreakerState(int failureThreshold, TimeSpan? openDuration, TimeProvider? timeProvider)

    Initializes a new instance of the `CircuitBreakerState` class with a custom `TimeProvider`.

    failureThreshold: int
    The number of consecutive failures before opening the circuit.
    openDuration: TimeSpan?
    The duration the circuit stays open. Defaults to 30 seconds.
    timeProvider: TimeProvider?
    The time provider to use for time measurements.

    Exceptions: ArgumentOutOfRangeException: `failureThreshold` is less than or equal to 0

  • methodAllowRequest
    public bool AllowRequest()

    Determines whether a publish attempt is permitted based on the current circuit state.

    Retorna: `true` if the circuit is in the Closed or HalfOpen state; otherwise, `false`.

  • methodRecordFailure
    public void RecordFailure()

    Records a failed publish call, incrementing the failure counter; opens the circuit immediately when in HalfOpen state or when the failure threshold is reached.

  • methodRecordSuccess
    public void RecordSuccess()

    Records a successful publish call, resetting the failure counter and closing the circuit.

  • propertyFailureThreshold
    public int FailureThreshold { get; }

    Gets the number of consecutive failures required before the circuit transitions to the Open state.

  • propertyOpenDuration
    public TimeSpan OpenDuration { get; }

    Gets the duration the circuit remains in the Open state before transitioning to HalfOpen and allowing a probe attempt.

  • propertyState
    public CircuitState State { get; }

    Gets the current state of the circuit breaker, automatically transitioning from Open to HalfOpen when the open duration has elapsed.

enum

CircuitState

Ensamblado: EricksonLopez.Outbox
public enum CircuitState

Represents the three states of a circuit breaker.

Miembros (3)

  • fieldClosed
    Closed

    Indicates normal operation where all publish calls pass through.

  • fieldHalfOpen
    HalfOpen

    Indicates that a probe period has elapsed and the next trial call is allowed through to test broker recovery.

  • fieldOpen
    Open

    Indicates that failure thresholds were exceeded and publish calls are rejected immediately.

class

ExponentialBackoffPolicy

Ensamblado: EricksonLopez.Outbox
public sealed class ExponentialBackoffPolicy : IRetryPolicy
Implementa: IRetryPolicy

Provides a retry policy that exponentially increases the delay between attempts. This prevents overwhelming a recovering network broker.

Miembros (3)

  • constructorExponentialBackoffPolicy
    public ExponentialBackoffPolicy(int maxAttempts = 10, int initialDelayMs = 100)

    Initializes a new instance of the `ExponentialBackoffPolicy` class.

    maxAttempts: int
    The maximum number of retry attempts.
    initialDelayMs: int
    The initial delay in milliseconds before the first retry.
  • methodGetNextDelay
    public TimeSpan GetNextDelay(int currentAttempt)

    Calculates the delay before the next retry attempt.

    currentAttempt: int
    The number of retry attempts made so far.

    Retorna: The time interval to wait before making the next attempt.

  • methodShouldRetry
    public bool ShouldRetry(int currentAttempt, Exception exception)

    Determines whether another retry should be attempted based on the current attempt count and the exception.

    currentAttempt: int
    The number of retry attempts made so far.
    exception: Exception
    The exception that caused the current attempt to fail.

    Retorna: `true` if the operation should be retried; otherwise, `false`.

record

ExponentialBackoffRetryPolicy

Ensamblado: EricksonLopez.Outbox
public sealed record ExponentialBackoffRetryPolicy(TimeSpan InitialDelay, int MaxAttempts, double Factor, TimeSpan? MaxDelay) : RetryPolicy
Hereda de: RetryPolicy

Represents a retry policy that exponentially backs off between attempts.

Miembros (6)

  • constructorExponentialBackoffRetryPolicy
    public ExponentialBackoffRetryPolicy(TimeSpan InitialDelay, int MaxAttempts, double Factor = 2.0, TimeSpan? MaxDelay = null)

    Initializes a new instance of ExponentialBackoffRetryPolicy.

    InitialDelay: TimeSpan
    The initial delay for the first retry attempt.
    MaxAttempts: int
    The maximum number of retry attempts.
    Factor: double
    The multiplier factor applied to the delay after each attempt.
    MaxDelay: TimeSpan?
    The maximum delay allowed. If the calculated delay exceeds this value, this value is used instead.
  • methodGetNextDelay
    public override TimeSpan? GetNextDelay(int currentAttempt)

    Gets the delay before the next retry attempt, or `null` if retries should stop.

    currentAttempt: int
    The current retry attempt count.

    Retorna: The `TimeSpan` to wait, or `null` to stop retrying.

  • propertyFactor
    public double Factor { get; init; }

    The multiplier factor applied to the delay after each attempt.

  • propertyInitialDelay
    public TimeSpan InitialDelay { get; init; }

    The initial delay for the first retry attempt.

  • propertyMaxAttempts
    public int MaxAttempts { get; init; }

    The maximum number of retry attempts.

  • propertyMaxDelay
    public TimeSpan? MaxDelay { get; init; }

    The maximum delay allowed. If the calculated delay exceeds this value, this value is used instead.

record

FixedDelayRetryPolicy

Ensamblado: EricksonLopez.Outbox
public sealed record FixedDelayRetryPolicy(TimeSpan Delay, int MaxAttempts) : RetryPolicy
Hereda de: RetryPolicy

Represents a retry policy that uses a fixed delay between attempts.

Miembros (4)

  • constructorFixedDelayRetryPolicy
    public FixedDelayRetryPolicy(TimeSpan Delay, int MaxAttempts)

    Initializes a new instance of FixedDelayRetryPolicy.

    Delay: TimeSpan
    The fixed delay to apply between attempts.
    MaxAttempts: int
    The maximum number of retry attempts.
  • methodGetNextDelay
    public override TimeSpan? GetNextDelay(int currentAttempt)

    Gets the delay before the next retry attempt, or `null` if retries should stop.

    currentAttempt: int
    The current retry attempt count.

    Retorna: The `TimeSpan` to wait, or `null` to stop retrying.

  • propertyDelay
    public TimeSpan Delay { get; init; }

    The fixed delay to apply between attempts.

  • propertyMaxAttempts
    public int MaxAttempts { get; init; }

    The maximum number of retry attempts.

interface

IRetryPolicy

Ensamblado: EricksonLopez.Outbox
public interface IRetryPolicy

Defines a policy for retrying failed dispatch operations.

Miembros (2)

  • methodGetNextDelay
    TimeSpan GetNextDelay(int currentAttempt)

    Calculates the delay before the next retry attempt.

    currentAttempt: int
    The number of retry attempts made so far.

    Retorna: The time interval to wait before making the next attempt.

  • methodShouldRetry
    bool ShouldRetry(int currentAttempt, Exception exception)

    Determines whether another retry should be attempted based on the current attempt count and the exception.

    currentAttempt: int
    The number of retry attempts made so far.
    exception: Exception
    The exception that caused the current attempt to fail.

    Retorna: `true` if the operation should be retried; otherwise, `false`.

record

JitterRetryPolicy

Ensamblado: EricksonLopez.Outbox
public sealed record JitterRetryPolicy(TimeSpan InitialDelay, int MaxAttempts, double Factor, TimeSpan? MaxDelay, double JitterFactor) : RetryPolicy
Hereda de: RetryPolicy

Represents a retry policy that applies exponential backoff with random jitter to prevent the thundering-herd problem when multiple dispatcher instances retry concurrently after a shared failure.

Miembros (7)

  • constructorJitterRetryPolicy
    public JitterRetryPolicy(TimeSpan InitialDelay, int MaxAttempts, double Factor = 2.0, TimeSpan? MaxDelay = null, double JitterFactor = 0.25)

    Initializes a new instance of JitterRetryPolicy.

    InitialDelay: TimeSpan
    The base delay for the first retry attempt, before the exponential factor is applied.
    MaxAttempts: int
    The maximum number of retry attempts before the policy stops retrying.
    Factor: double
    The multiplier applied to the delay after each consecutive attempt. Defaults to `2.0` (doubles each attempt).
    MaxDelay: TimeSpan?
    The upper bound on the calculated delay. If `null`, no cap is applied.
    JitterFactor: double
    The fraction of the base delay to use as the jitter window, distributed as ±`JitterFactor` of the base. Defaults to `0.25`.
  • methodGetNextDelay
    public override TimeSpan? GetNextDelay(int currentAttempt)

    Gets the delay before the next retry attempt, or `null` if retries should stop.

    currentAttempt: int
    The current retry attempt count.

    Retorna: The `TimeSpan` to wait, or `null` to stop retrying.

  • propertyFactor
    public double Factor { get; init; }

    The multiplier applied to the delay after each consecutive attempt. Defaults to `2.0` (doubles each attempt).

  • propertyInitialDelay
    public TimeSpan InitialDelay { get; init; }

    The base delay for the first retry attempt, before the exponential factor is applied.

  • propertyJitterFactor
    public double JitterFactor { get; init; }

    The fraction of the base delay to use as the jitter window, distributed as ±`JitterFactor` of the base. Defaults to `0.25`.

  • propertyMaxAttempts
    public int MaxAttempts { get; init; }

    The maximum number of retry attempts before the policy stops retrying.

  • propertyMaxDelay
    public TimeSpan? MaxDelay { get; init; }

    The upper bound on the calculated delay. If `null`, no cap is applied.

class

RetryDispatcherInterceptor

Ensamblado: EricksonLopez.Outbox
public sealed partial class RetryDispatcherInterceptor : IBrokerPublisher
Implementa: IBrokerPublisher

Provides an interceptor that wraps the broker publishing process and applies the configured `RetryPolicy`. Uses a shared retry loop via `ExecuteWithRetryAsync` to avoid code duplication between the generic and raw publish paths.

Miembros (2)

  • constructorRetryDispatcherInterceptor
    public RetryDispatcherInterceptor(IBrokerPublisher inner, RetryPolicy policy, CircuitBreakerState circuitBreaker, ILogger<RetryDispatcherInterceptor> logger)

    Initializes a new instance of the `RetryDispatcherInterceptor` class.

    inner: IBrokerPublisher
    The underlying broker publisher.
    policy: RetryPolicy
    The retry policy to apply.
    circuitBreaker: CircuitBreakerState
    The circuit breaker state tracker.
    logger: ILogger<RetryDispatcherInterceptor>
    The logger instance.
  • methodPublishRawAsync
    public ValueTask<DispatchResult> PublishRawAsync(OutboxMessage message, OutboxMessageMetadata metadata, DispatchContext context)

    Publishes a raw serialized outbox message as-is.

    message: OutboxMessage
    The raw outbox message to publish.
    metadata: OutboxMessageMetadata
    The metadata associated with the message.
    context: DispatchContext
    The context governing the dispatch operation, including cancellation tokens.

    Retorna: A task that represents the asynchronous dispatch operation, containing the `DispatchResult`.

    Used by the Dispatcher which works with pre-serialized payloads, avoiding runtime generics and reflection for NativeAOT compatibility. DispatchResult contract for implementers: **Scenario**: **Return value**: - **Message published successfully**: **`DispatchResult.Ok()`**: - **Transient / recoverable failure (network timeout, broker unreachable, rate-limited)**: **`DispatchResult.FailAndRetry(exception)`**: - **Fatal / unrecoverable failure (schema mismatch, serialization error, message too large for broker, authorization denied)**: **`DispatchResult.FailFatal(exception)`**: Do NOT throw exceptions here. Thrown exceptions are treated as fatal failures by the dispatcher (equivalent to `DispatchResult.FailFatal`). Always catch broker exceptions and map them to the appropriate `DispatchResult`. Do NOT return `default(DispatchResult)`. The default value of the struct (`Success=false, ShouldRetry=false, Error=null`) is an invalid state that will cause the dispatcher to dead-letter the message with a misleading "no error" state. Always use one of the factory methods: `DispatchResult.Ok()`, `DispatchResult.FailAndRetry(ex)`, or `DispatchResult.FailFatal(ex)`. The dispatcher wraps calls to the publisher with a retry interceptor, which automatically retries `FailAndRetry` results with exponential backoff. Returning `FailFatal` bypasses retry and dead-letters the message immediately. OpenTelemetry — `messaging.system` tag requirement: The outbox core sets `messaging.system = "outbox"` as a default on the dispatch Activity. Broker implementers MUST override this tag with the actual broker name: `System.Diagnostics.Activity.Current?.SetTag("messaging.system", "rabbitmq"); // or "kafka", "azure_service_bus", etc.` This is required by the OpenTelemetry Messaging Semantic Conventions (v1.26+): https://opentelemetry.io/docs/specs/semconv/messaging/messaging-spans/#messaging-attributes

record

RetryPolicy

Ensamblado: EricksonLopez.Outbox
public abstract record RetryPolicy

Defines the base contract for a retry policy used when publishing messages.

Miembros (2)

  • methodGetNextDelay
    public abstract TimeSpan? GetNextDelay(int currentAttempt)

    Gets the delay before the next retry attempt, or `null` if retries should stop.

    currentAttempt: int
    The current retry attempt count.

    Retorna: The `TimeSpan` to wait, or `null` to stop retrying.

  • propertyDefault
    public static RetryPolicy Default { get; }

    Gets the default retry policy: exponential backoff starting at 1 second, capped at 30 seconds, with a maximum of 5 attempts.

    Suitable for most transient broker failure scenarios.

EricksonLopez.Outbox.Serialization#

5
class

DefaultOutboxJsonSerializer

Ensamblado: EricksonLopez.Outbox
public sealed class DefaultOutboxJsonSerializer : IOutboxSerializer
Implementa: IOutboxSerializer

UTF-8 JSON `IOutboxSerializer` with a raw UTF-8 passthrough fast path when the message type is `string` (preventing double-escaped JSON string literals when pre-serialized JSON payloads are enqueued). For strict Native AOT source-generated serialization, prefer `NativeAotJsonSerializer`.

Miembros (4)

  • constructorDefaultOutboxJsonSerializer
    public DefaultOutboxJsonSerializer(JsonSerializerOptions? options = null)

    Initializes a new instance of the `DefaultOutboxJsonSerializer` class.

    options: JsonSerializerOptions?
    Optional `JsonSerializerOptions`.
  • methodDeserialize<TMessage>
    public TMessage Deserialize<TMessage>(ReadOnlySpan<byte> data)

    Deserializes a message of the specified type from a UTF-8 byte span.

    data: ReadOnlySpan<byte>
    The read-only span of bytes containing the serialized message data.

    Retorna: The deserialized message instance.

    Type parameters: TMessage: The expected type of the deserialized message.

  • methodSerialize<TMessage>
    public ReadOnlyMemory<byte> Serialize<TMessage>(TMessage message)

    Serializes the specified message payload into a byte array payload. Exposes a `ReadOnlyMemory<T>` to avoid defensive array copying where possible.

    message: TMessage
    The message to serialize.

    Retorna: A read-only memory region containing the UTF-8 encoded bytes of the serialized message.

    Type parameters: TMessage: The type of the message being serialized.

  • methodSerialize<TMessage>
    public void Serialize<TMessage>(TMessage message, IBufferWriter<byte> buffer)

    Serializes the specified message directly into the provided buffer writer.

    message: TMessage
    The message to serialize.
    buffer: IBufferWriter<byte>
    The buffer writer to which the serialized message bytes are written.

    Avoids heap allocations for intermediate byte arrays by writing directly to the buffer. Implementations should override it for maximum throughput on hot paths. The default implementation serializes into an intermediate byte array. Type parameters: TMessage: The type of the message being serialized.

interface

IOutboxMessageTypeResolver

Ensamblado: EricksonLopez.Outbox
public interface IOutboxMessageTypeResolver

Defines a contract for mapping logical message type aliases to CLR types and vice versa.

Notas:

This indirection solves a critical versioning problem: if a class is renamed or moved to a different namespace/assembly, the alias stored in the database remains stable. The application only needs to update the mapping registry, not perform a data migration. Designed to be registered once at startup and used read-only afterwards (thread-safe by construction).

Miembros (6)

  • methodGetAlias
    string GetAlias(Type messageType)

    Resolves a CLR type to its registered alias string.

    messageType: Type
    The CLR type of the message to resolve.

    Retorna: The registered alias string.

    Exceptions: InvalidOperationException: The specified type has not been registered

  • methodGetAlias<TMessage>
    string GetAlias<TMessage>() where TMessage : notnull

    Resolves the alias for the specified generic message type.

    Retorna: The registered alias string.

    Type parameters: TMessage: The generic type of the message to resolve. Exceptions: InvalidOperationException: The specified type has not been registered

  • methodGetAllMappings
    IReadOnlyDictionary<string, Type> GetAllMappings()

    Retrieves all registered alias-to-type mappings.

    Retorna: A read-only dictionary containing all registered mappings.

  • methodResolve
    Type? Resolve(string alias)

    Resolves the alias string to its corresponding CLR type.

    alias: string
    The stable string alias identifying the message type.

    Retorna: The resolved `Type` if found; otherwise, `null`.

  • methodTryGetAlias
    bool TryGetAlias(Type messageType, out string? alias)

    Resolves a CLR type to its registered alias string without throwing an exception on missing registration.

    messageType: Type
    The CLR type of the message to resolve.
    alias: out string?
    When it returns, contains the registered alias string if found; otherwise, `null`.

    Retorna: `true` if the alias was found; otherwise, `false`.

  • methodTryGetAlias<TMessage>
    bool TryGetAlias<TMessage>(out string? alias) where TMessage : notnull

    Resolves the alias for the specified generic message type without requiring a runtime type lookup.

    alias: out string?
    When it returns, contains the registered alias string if found; otherwise, `null`.

    Retorna: `true` if the alias was found; otherwise, `false`.

    Type parameters: TMessage: The generic type of the message to resolve.

interface

IOutboxSerializer

Ensamblado: EricksonLopez.Outbox.Abstractions
public interface IOutboxSerializer

Defines an abstraction for serializing outbox messages before they are stored in the database or dispatched over the network.

Miembros (3)

  • methodDeserialize<TMessage>
    TMessage Deserialize<TMessage>(ReadOnlySpan<byte> data)

    Deserializes a message of the specified type from a UTF-8 byte span.

    data: ReadOnlySpan<byte>
    The read-only span of bytes containing the serialized message data.

    Retorna: The deserialized message instance.

    Type parameters: TMessage: The expected type of the deserialized message.

  • methodSerialize<TMessage>
    ReadOnlyMemory<byte> Serialize<TMessage>(TMessage message)

    Serializes the specified message payload into a byte array payload. Exposes a `ReadOnlyMemory<T>` to avoid defensive array copying where possible.

    message: TMessage
    The message to serialize.

    Retorna: A read-only memory region containing the UTF-8 encoded bytes of the serialized message.

    Type parameters: TMessage: The type of the message being serialized.

  • methodSerialize<TMessage>
    void Serialize<TMessage>(TMessage message, IBufferWriter<byte> buffer)

    Serializes the specified message directly into the provided buffer writer.

    message: TMessage
    The message to serialize.
    buffer: IBufferWriter<byte>
    The buffer writer to which the serialized message bytes are written.

    Avoids heap allocations for intermediate byte arrays by writing directly to the buffer. Implementations should override it for maximum throughput on hot paths. The default implementation serializes into an intermediate byte array. Type parameters: TMessage: The type of the message being serialized.

class

InMemoryMessageTypeResolver

Ensamblado: EricksonLopez.Outbox
public sealed class InMemoryMessageTypeResolver : IOutboxMessageTypeResolver
Implementa: IOutboxMessageTypeResolver

Provides a default in-memory implementation of `IOutboxMessageTypeResolver`.

Miembros (5)

  • constructorInMemoryMessageTypeResolver
    public InMemoryMessageTypeResolver(IEnumerable<(string alias, Type type)> mappings)

    Initializes a new instance of the `InMemoryMessageTypeResolver` class with the specified mappings.

    mappings: IEnumerable<(string alias, Type type)>
    The collection of alias-to-type pairs to register.

    Exceptions: ArgumentException: An alias in the mappings is null or whitespace

  • methodGetAlias
    public string GetAlias(Type messageType)

    Resolves a CLR type to its registered alias string.

    messageType: Type
    The CLR type of the message to resolve.

    Retorna: The registered alias string.

    Exceptions: InvalidOperationException: The specified type has not been registered

  • methodGetAllMappings
    public IReadOnlyDictionary<string, Type> GetAllMappings()

    Retrieves all registered alias-to-type mappings.

    Retorna: A read-only dictionary containing all registered mappings.

  • methodResolve
    public Type? Resolve(string alias)

    Resolves the alias string to its corresponding CLR type.

    alias: string
    The stable string alias identifying the message type.

    Retorna: The resolved `Type` if found; otherwise, `null`.

  • methodTryGetAlias
    public bool TryGetAlias(Type messageType, out string? alias)

    Resolves a CLR type to its registered alias string without throwing an exception on missing registration.

    messageType: Type
    The CLR type of the message to resolve.
    alias: out string?
    When it returns, contains the registered alias string if found; otherwise, `null`.

    Retorna: `true` if the alias was found; otherwise, `false`.

class

NativeAotJsonSerializer

Ensamblado: EricksonLopez.Outbox
public sealed class NativeAotJsonSerializer : IOutboxSerializer
Implementa: IOutboxSerializer

Provides a strict NativeAOT-compatible JSON serializer. It bans runtime reflection completely by requiring a pre-compiled `JsonSerializerContext`.

Miembros (4)

  • constructorNativeAotJsonSerializer
    public NativeAotJsonSerializer(JsonSerializerContext context)

    Initializes a new instance of the `NativeAotJsonSerializer` class.

    context: JsonSerializerContext
    The pre-compiled `JsonSerializerContext` containing type info.

    For NativeAOT compatibility without IL2026/IL2057 warnings, the provided `context` must be generated by the System.Text.Json source generator and include all message types.

  • methodDeserialize<TMessage>
    public TMessage Deserialize<TMessage>(ReadOnlySpan<byte> data)

    Deserializes a message of the specified type from a UTF-8 byte span.

    data: ReadOnlySpan<byte>
    The read-only span of bytes containing the serialized message data.

    Retorna: The deserialized message instance.

    Type parameters: TMessage: The expected type of the deserialized message.

  • methodSerialize<TMessage>
    public ReadOnlyMemory<byte> Serialize<TMessage>(TMessage message)

    Serializes the specified message payload into a byte array payload. Exposes a `ReadOnlyMemory<T>` to avoid defensive array copying where possible.

    message: TMessage
    The message to serialize.

    Retorna: A read-only memory region containing the UTF-8 encoded bytes of the serialized message.

    Type parameters: TMessage: The type of the message being serialized.

  • methodSerialize<TMessage>
    public void Serialize<TMessage>(TMessage message, IBufferWriter<byte> buffer)

    Serializes the specified message directly into the provided buffer writer without allocating an intermediate `byte[]`.

    message: TMessage
    The message instance to serialize.
    buffer: IBufferWriter<byte>
    The target buffer writer receiving the serialized bytes.

    This is the preferred path for `DefaultOutbox` when writing to its `ThreadStatic` payload buffer. Type parameters: TMessage: The type of the message being serialized.

EricksonLopez.Outbox.Serialization.MessagePack#

2
class

MessagePackOutboxSerializationExtensions

Ensamblado: EricksonLopez.Outbox.Serialization.MessagePack
public static class MessagePackOutboxSerializationExtensions

Provides extension methods for configuring MessagePack serialization for the outbox.

Miembros (1)

  • methodUseMessagePackSerializer
    public static OutboxOptions UseMessagePackSerializer(this OutboxOptions options, MessagePackSerializerOptions? messagePackOptions = null)

    Configures the outbox to use MessagePack (`MessagePackOutboxSerializer`) for payload serialization.

    options: this OutboxOptions
    The outbox options builder.
    messagePackOptions: MessagePackSerializerOptions?
    Optional custom MessagePack serialization options.

    Retorna: The outbox options builder for method chaining.

    Exceptions: ArgumentNullException: `options` is `null`

class

MessagePackOutboxSerializer

Ensamblado: EricksonLopez.Outbox.Serialization.MessagePack
public sealed class MessagePackOutboxSerializer : IOutboxSerializer
Implementa: IOutboxSerializer

Provides a high-performance, compact binary serializer implementation using MessagePack.

Miembros (4)

  • constructorMessagePackOutboxSerializer
    public MessagePackOutboxSerializer(MessagePackSerializerOptions? options = null)

    Initializes a new instance of the `MessagePackOutboxSerializer` class.

    options: MessagePackSerializerOptions?
    Optional MessagePack serializer options (defaults to `MessagePackSerializerOptions.Standard`).
  • methodDeserialize<TMessage>
    public TMessage Deserialize<TMessage>(ReadOnlySpan<byte> data)

    Deserializes a message of the specified type from a UTF-8 byte span.

    data: ReadOnlySpan<byte>
    The read-only span of bytes containing the serialized message data.

    Retorna: The deserialized message instance.

    Type parameters: TMessage: The expected type of the deserialized message.

  • methodSerialize<TMessage>
    public ReadOnlyMemory<byte> Serialize<TMessage>(TMessage message)

    Serializes the specified message payload into a byte array payload. Exposes a `ReadOnlyMemory<T>` to avoid defensive array copying where possible.

    message: TMessage
    The message to serialize.

    Retorna: A read-only memory region containing the UTF-8 encoded bytes of the serialized message.

    Type parameters: TMessage: The type of the message being serialized.

  • methodSerialize<TMessage>
    public void Serialize<TMessage>(TMessage message, IBufferWriter<byte> buffer)

    Serializes the specified message directly into the provided buffer writer.

    message: TMessage
    The message to serialize.
    buffer: IBufferWriter<byte>
    The buffer writer to which the serialized message bytes are written.

    Avoids heap allocations for intermediate byte arrays by writing directly to the buffer. Implementations should override it for maximum throughput on hot paths. The default implementation serializes into an intermediate byte array. Type parameters: TMessage: The type of the message being serialized.

EricksonLopez.Outbox.Serialization.Protobuf#

2
class

ProtobufOutboxSerializationExtensions

Ensamblado: EricksonLopez.Outbox.Serialization.Protobuf
public static class ProtobufOutboxSerializationExtensions

Provides extension methods for configuring Protocol Buffers serialization for the outbox.

Miembros (1)

  • methodUseProtobufSerializer
    public static OutboxOptions UseProtobufSerializer(this OutboxOptions options)

    Configures the outbox to use Protocol Buffers (`ProtobufOutboxSerializer`) for payload serialization.

    options: this OutboxOptions
    The outbox options builder.

    Retorna: The outbox options builder for method chaining.

    Exceptions: ArgumentNullException: `options` is `null`

class

ProtobufOutboxSerializer

Ensamblado: EricksonLopez.Outbox.Serialization.Protobuf
public sealed class ProtobufOutboxSerializer : IOutboxSerializer
Implementa: IOutboxSerializer

Provides a high-performance, compact binary serializer implementation using Protocol Buffers (protobuf-net).

Miembros (3)

  • methodDeserialize<TMessage>
    public TMessage Deserialize<TMessage>(ReadOnlySpan<byte> data)

    Deserializes a message of the specified type from a UTF-8 byte span.

    data: ReadOnlySpan<byte>
    The read-only span of bytes containing the serialized message data.

    Retorna: The deserialized message instance.

    Type parameters: TMessage: The expected type of the deserialized message.

  • methodSerialize<TMessage>
    public ReadOnlyMemory<byte> Serialize<TMessage>(TMessage message)

    Serializes the specified message payload into a byte array payload. Exposes a `ReadOnlyMemory<T>` to avoid defensive array copying where possible.

    message: TMessage
    The message to serialize.

    Retorna: A read-only memory region containing the UTF-8 encoded bytes of the serialized message.

    Type parameters: TMessage: The type of the message being serialized.

  • methodSerialize<TMessage>
    public void Serialize<TMessage>(TMessage message, IBufferWriter<byte> buffer)

    Serializes the specified message directly into the provided buffer writer.

    message: TMessage
    The message to serialize.
    buffer: IBufferWriter<byte>
    The buffer writer to which the serialized message bytes are written.

    Avoids heap allocations for intermediate byte arrays by writing directly to the buffer. Implementations should override it for maximum throughput on hot paths. The default implementation serializes into an intermediate byte array. Type parameters: TMessage: The type of the message being serialized.

EricksonLopez.Outbox.SourceGenerators#

1
class

OutboxTypeMappingGenerator

Ensamblado: EricksonLopez.Outbox.SourceGenerators
public sealed class OutboxTypeMappingGenerator : IIncrementalGenerator
Implementa: IIncrementalGenerator

Provides a source generator that scans for types annotated with `OutboxMessageAttribute` and generates an optimized type resolver and registration extensions.

Miembros (2)

  • constructorOutboxTypeMappingGenerator
    public OutboxTypeMappingGenerator()

    Initializes a new instance of the `OutboxTypeMappingGenerator` class.

  • methodInitialize
    public void Initialize(IncrementalGeneratorInitializationContext context)

    Inherits documentation from base type or interface.

    context: IncrementalGeneratorInitializationContext

EricksonLopez.Outbox.Storage.MariaDb#

4
class

MariaDbDeadLetterRepository

Ensamblado: EricksonLopez.Outbox.Storage.MariaDb
public sealed class MariaDbDeadLetterRepository : IDeadLetterRepository
Implementa: IDeadLetterRepository

Provides a MariaDB implementation of `IDeadLetterRepository`.

Miembros (6)

  • constructorMariaDbDeadLetterRepository
    public MariaDbDeadLetterRepository(Func<IDbConnection> connectionFactory, IOptionsMonitor<OutboxRuntimeOptions> options)

    Initializes a new instance of the `MariaDbDeadLetterRepository` class.

    connectionFactory: Func<IDbConnection>
    The factory that creates MariaDB connections.
    options: IOptionsMonitor<OutboxRuntimeOptions>
    The outbox runtime options.

    Exceptions: ArgumentNullException: `connectionFactory` or `options` is `null`

  • methodDeleteAsync
    public async ValueTask DeleteAsync(Guid id, CancellationToken cancellationToken = default)

    Deletes a dead-lettered message by its unique identifier.

    id: Guid
    The unique identifier of the dead-lettered message to delete.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • methodGetAsync
    public async ValueTask<IReadOnlyList<DeadLetterMessage>> GetAsync(int limit = 100, DateTimeOffset? after = null, CancellationToken cancellationToken = default)

    Retrieves a page of dead-lettered messages for inspection or replay.

    limit: int
    The maximum number of records to return.
    after: DateTimeOffset?
    The cursor indicating to return records dead-lettered after this timestamp. Pass `DateTimeOffset.MinValue` for the first page.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the retrieved page of dead-lettered messages.

  • methodInsertAsync
    public async ValueTask InsertAsync(DeadLetterMessage message, IOutboxTransactionContext? transaction = default, CancellationToken cancellationToken = default)

    Persists a dead-lettered message.

    message: DeadLetterMessage
    The dead-lettered message to persist.
    transaction: IOutboxTransactionContext?
    The optional transaction context. If `null`, the repository must open its own connection and auto-commit the insert.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Called by the Dispatcher after a message has exhausted its `Retry.RetryPolicy`.

  • methodPurgeAsync
    public async ValueTask PurgeAsync(DateTimeOffset olderThan, CancellationToken cancellationToken = default)

    Purges all dead-lettered messages older than the specified timestamp.

    olderThan: DateTimeOffset
    The timestamp threshold; messages older than this value will be purged.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • propertyIsFirstPartyImplementation
    public bool IsFirstPartyImplementation { get; }

    Gets a value indicating whether this is a first-party (built-in) implementation.

    Used by `OutboxStartupValidator` to warn operators when a third-party `IDeadLetterRepository` is registered, reminding them to verify that their implementation correctly handles `transaction = null` (auto-commit mode). All first-party storage engine implementations override this to return `true`. Third-party implementations that do not override this will return `false`, triggering the startup advisory log message. This is a Zero-Reflection pattern: no `GetType().Name`, no string comparisons, no assembly scanning. The check is a simple virtual dispatch.

class

MariaDbIdempotencyRepository

Ensamblado: EricksonLopez.Outbox.Storage.MariaDb
public sealed class MariaDbIdempotencyRepository : IIdempotencyRepository
Implementa: IIdempotencyRepository

Provides a MariaDB implementation of `IIdempotencyRepository`.

Miembros (3)

  • constructorMariaDbIdempotencyRepository
    public MariaDbIdempotencyRepository(Func<IDbConnection> connectionFactory, IOptionsMonitor<OutboxRuntimeOptions> options)

    Initializes a new instance of the `MariaDbIdempotencyRepository` class.

    connectionFactory: Func<IDbConnection>
    The factory that creates MariaDB connections.
    options: IOptionsMonitor<OutboxRuntimeOptions>
    The outbox runtime options.

    Exceptions: ArgumentNullException: `connectionFactory` or `options` is `null`

  • methodPurgeExpiredRecordsAsync
    public async ValueTask PurgeExpiredRecordsAsync(DateTimeOffset olderThan, CancellationToken cancellationToken = default)

    Purges idempotency records older than the specified timestamp.

    olderThan: DateTimeOffset
    The timestamp threshold; records older than this value will be purged.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Called periodically by `InboxCleanupService` to prevent table bloat.

  • methodTryInsertAsync
    public async ValueTask<bool> TryInsertAsync(IdempotencyRecord record, IOutboxTransactionContext? transaction = default, CancellationToken cancellationToken = default)

    Attempts to insert an idempotency record.

    record: IdempotencyRecord
    The idempotency record to insert.
    transaction: IOutboxTransactionContext?
    The optional transaction context.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result is `true` if the record was inserted; otherwise, `false` if the record already exists (duplicate).

class

MariaDbOutboxRepository

Ensamblado: EricksonLopez.Outbox.Storage.MariaDb
public sealed class MariaDbOutboxRepository : IOutboxRepository
Implementa: IOutboxRepository

Provides a MariaDB-specific implementation of `IOutboxRepository`.

Notas:

Although MariaDB shares the `MySqlConnector` driver with MySQL, this implementation uses a plain multi-row `INSERT IGNORE` for batch inserts instead of `MySqlBulkCopy`, which is not supported by MariaDB.

Miembros (9)

  • constructorMariaDbOutboxRepository
    public MariaDbOutboxRepository(Func<IDbConnection> connectionFactory, IOptions<OutboxRuntimeOptions>? options = null)

    Initializes a new instance of the `MariaDbOutboxRepository` class.

    connectionFactory: Func<IDbConnection>
    The factory that creates MariaDB connections.
    options: IOptions<OutboxRuntimeOptions>?
    The runtime options containing thresholds and configurations.

    Exceptions: ArgumentNullException: `connectionFactory` is `null`

  • methodFetchPendingAsync
    public async ValueTask<IReadOnlyList<OutboxMessage>> FetchPendingAsync(int batchSize, CancellationToken cancellationToken = default)

    Retrieves a batch of pending messages ready for delivery.

    batchSize: int
    The maximum number of messages to retrieve.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the batch of messages retrieved.

    The method fetches up to the specified batch size of messages that are in the Pending state (0) and whose delivery time is less than or equal to the current UTC time. Implementations guarantee safe concurrent polling by using SKIP LOCKED or equivalent semantics, atomically transitioning the fetched messages to the InFlight state (1). Scheduling edge case — `deliver_at` vs `MaxMessageAge`: Messages stored with a future `deliver_at` timestamp that exceeds `MaxMessageAge` will be silently excluded from polling by the `created_at` age guard. Such messages will not be processed and will not be automatically dead-lettered. Ensure `OutboxRuntimeOptions.MaxMessageAge` is greater than the maximum `deliver_at` offset used in your application (e.g., if scheduling up to 7 days ahead, set `MaxMessageAge ≥ 8 days`). Ordering with multiple dispatcher instances: When multiple dispatcher instances run concurrently, messages are fetched in `ORDER BY created_at ASC, id ASC` order but can be claimed by different instances via `SKIP LOCKED`, resulting in non-deterministic global ordering. In partitioned table setups, the order guarantee applies within each partition only. For strict global ordering, use a single dispatcher instance with `MaxDegreeOfParallelism = 1`.

  • methodGetPendingCountAsync
    public async ValueTask<long> GetPendingCountAsync(CancellationToken cancellationToken = default)

    Retrieves the approximate count of messages awaiting processing.

    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the approximate pending message count.

    Includes messages in the Pending (0) or Failed (3) states for metrics and monitoring.

  • methodInsertAsync
    public async ValueTask InsertAsync(OutboxMessage record, IOutboxTransactionContext transaction, CancellationToken cancellationToken = default)

    Inserts a single message into the outbox table atomically within the specified transaction.

    record: OutboxMessage
    The message to insert into the outbox.
    transaction: IOutboxTransactionContext
    The context representing the active database transaction.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • methodInsertBatchAsync
    public async ValueTask InsertBatchAsync(ReadOnlyMemory<OutboxMessage> records, IOutboxTransactionContext transaction, CancellationToken cancellationToken = default)

    Inserts a batch of messages into the outbox table in a single round-trip.

    records: ReadOnlyMemory<OutboxMessage>
    The batch of messages to insert.
    transaction: IOutboxTransactionContext
    The context representing the active database transaction.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    MariaDB does not support `MySqlBulkCopy` (which relies on the MySQL-specific `LOCAL INFILE` protocol). This implementation uses a standard multi-row `INSERT IGNORE INTO … VALUES (…),(…)` statement instead.

  • methodMarkAsDispatchedAsync
    public async ValueTask MarkAsDispatchedAsync(IReadOnlyList<OutboxMessage> messages, CancellationToken cancellationToken = default)

    Atomically marks the specified messages as successfully dispatched.

    messages: IReadOnlyList<OutboxMessage>
    The collection of messages to mark as dispatched.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • methodMarkAsFailedAsync
    public async ValueTask MarkAsFailedAsync(IReadOnlyList<OutboxMessage> messages, string error, bool isDeadLetter = false, CancellationToken cancellationToken = default)

    Marks the specified messages as failed, updating their error details and retry counts.

    messages: IReadOnlyList<OutboxMessage>
    The collection of messages that failed to process.
    error: string
    The error message or exception details causing the failure.
    isDeadLetter: bool
    `true` to mark the messages as permanently failed (dead letter); otherwise, `false`.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Is typically invoked by `Retry.RetryDispatcherInterceptor` when publishing fails. If the maximum retry attempts are exhausted, the message may be marked as a dead letter. Security Warning: The `error` parameter may contain sensitive information (such as connection strings in stack traces). Ensure exceptions are sanitized in production environments before they are persisted, to prevent leaking sensitive data.

  • methodPurgeDispatchedMessagesAsync
    public async ValueTask<int> PurgeDispatchedMessagesAsync(DateTimeOffset cutoff, int batchSize = 1000, CancellationToken cancellationToken = default)

    Purges dispatched messages that were processed prior to the specified cutoff timestamp. Used by `Hosting.OutboxCleanupService` when `DeleteOnDispatch = false`.

    cutoff: DateTimeOffset
    The cutoff timestamp; messages dispatched prior to this time will be deleted.
    batchSize: int
    The maximum number of rows to delete in a single batch.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation, returning the number of purged rows.

  • methodReclaimStaleMessagesAsync
    public async ValueTask<int> ReclaimStaleMessagesAsync(TimeSpan staleTimeout, CancellationToken cancellationToken = default)

    Reclaims messages that have remained in the InFlight state longer than the specified timeout.

    staleTimeout: TimeSpan
    The duration after which an InFlight message is considered abandoned.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the number of messages reclaimed.

    This mechanism prevents message loss if a dispatcher crashes after claiming a batch (transitioning from state 0 to 1) but before marking it as dispatched. Implementations must atomically reset these messages to the Pending state (0) if their last updated time is older than the current UTC time minus the stale timeout.

class

MariaDbOutboxSetup

Ensamblado: EricksonLopez.Outbox.Storage.MariaDb
public static class MariaDbOutboxSetup

Provides extension methods for configuring MariaDB outbox storage.

Miembros (1)

  • methodUseMariaDb
    public static OutboxOptions UseMariaDb(this OutboxOptions options, Func<IServiceProvider, MySqlConnection> connectionFactory)

    Configures the outbox to use MariaDB as the storage engine using the provided connection factory.

    options: this OutboxOptions
    The outbox options being configured.
    connectionFactory: Func<IServiceProvider, MySqlConnection>
    A factory delegate to provide a `MySqlConnection` based on the `IServiceProvider`.

    Retorna: The original `OutboxOptions` for method chaining.

    Exceptions: ArgumentNullException: `options` or `connectionFactory` is `null`

EricksonLopez.Outbox.Storage.MongoDb#

4
class

MongoDbDeadLetterRepository

Ensamblado: EricksonLopez.Outbox.Storage.MongoDb
public sealed class MongoDbDeadLetterRepository : IDeadLetterRepository
Implementa: IDeadLetterRepository

Provides a MongoDB implementation of `IDeadLetterRepository`.

Miembros (6)

  • constructorMongoDbDeadLetterRepository
    public MongoDbDeadLetterRepository(IMongoDatabase database)

    Initializes a new instance of the `MongoDbDeadLetterRepository` class.

    database: IMongoDatabase
    The MongoDB database instance.

    Exceptions: ArgumentNullException: `database` is `null`

  • methodDeleteAsync
    public async ValueTask DeleteAsync(Guid id, CancellationToken cancellationToken = default)

    Deletes a dead-lettered message by its unique identifier.

    id: Guid
    The unique identifier of the dead-lettered message to delete.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • methodGetAsync
    public async ValueTask<IReadOnlyList<DeadLetterMessage>> GetAsync(int limit = 100, DateTimeOffset? after = null, CancellationToken cancellationToken = default)

    Retrieves a page of dead-lettered messages for inspection or replay.

    limit: int
    The maximum number of records to return.
    after: DateTimeOffset?
    The cursor indicating to return records dead-lettered after this timestamp. Pass `DateTimeOffset.MinValue` for the first page.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the retrieved page of dead-lettered messages.

  • methodInsertAsync
    public async ValueTask InsertAsync(DeadLetterMessage message, IOutboxTransactionContext? transaction = default, CancellationToken cancellationToken = default)

    Persists a dead-lettered message.

    message: DeadLetterMessage
    The dead-lettered message to persist.
    transaction: IOutboxTransactionContext?
    The optional transaction context. If `null`, the repository must open its own connection and auto-commit the insert.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Called by the Dispatcher after a message has exhausted its `Retry.RetryPolicy`.

  • methodPurgeAsync
    public async ValueTask PurgeAsync(DateTimeOffset olderThan, CancellationToken cancellationToken = default)

    Purges all dead-lettered messages older than the specified timestamp.

    olderThan: DateTimeOffset
    The timestamp threshold; messages older than this value will be purged.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • propertyIsFirstPartyImplementation
    public bool IsFirstPartyImplementation { get; }

    Gets a value indicating whether this is a first-party (built-in) implementation.

    Used by `OutboxStartupValidator` to warn operators when a third-party `IDeadLetterRepository` is registered, reminding them to verify that their implementation correctly handles `transaction = null` (auto-commit mode). All first-party storage engine implementations override this to return `true`. Third-party implementations that do not override this will return `false`, triggering the startup advisory log message. This is a Zero-Reflection pattern: no `GetType().Name`, no string comparisons, no assembly scanning. The check is a simple virtual dispatch.

class

MongoDbOutboxExtensions

Ensamblado: EricksonLopez.Outbox.Storage.MongoDb
public static class MongoDbOutboxExtensions

Provides extension methods for registering MongoDB outbox storage.

Miembros (1)

  • methodAddMongoDbOutbox
    public static IServiceCollection AddMongoDbOutbox(this IServiceCollection services, Func<IServiceProvider, IMongoDatabase> databaseFactory)

    Registers MongoDB as the outbox storage and dead-letter queue repository.

    services: this IServiceCollection
    The service collection.
    databaseFactory: Func<IServiceProvider, IMongoDatabase>
    Factory to resolve `IMongoDatabase`.

    Retorna: The service collection for chaining.

    Exceptions: ArgumentNullException: `services` or `databaseFactory` is `null`

class

MongoDbOutboxRepository

Ensamblado: EricksonLopez.Outbox.Storage.MongoDb
public sealed class MongoDbOutboxRepository : IOutboxRepository
Implementa: IOutboxRepository

Provides a MongoDB implementation of `IOutboxRepository` using native BSON documents for AOT safety.

Miembros (10)

  • constructorMongoDbOutboxRepository
    public MongoDbOutboxRepository(IMongoDatabase database, IOptions<OutboxRuntimeOptions>? options = null)

    Initializes a new instance of the `MongoDbOutboxRepository` class.

    database: IMongoDatabase
    The MongoDB database instance.
    options: IOptions<OutboxRuntimeOptions>?
    Optional outbox runtime options.

    Exceptions: ArgumentNullException: `database` is `null`

  • methodFetchPendingAsync
    public async ValueTask<IReadOnlyList<OutboxMessage>> FetchPendingAsync(int batchSize, CancellationToken cancellationToken = default)

    Retrieves a batch of pending messages ready for delivery.

    batchSize: int
    The maximum number of messages to retrieve.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the batch of messages retrieved.

    The method fetches up to the specified batch size of messages that are in the Pending state (0) and whose delivery time is less than or equal to the current UTC time. Implementations guarantee safe concurrent polling by using SKIP LOCKED or equivalent semantics, atomically transitioning the fetched messages to the InFlight state (1). Scheduling edge case — `deliver_at` vs `MaxMessageAge`: Messages stored with a future `deliver_at` timestamp that exceeds `MaxMessageAge` will be silently excluded from polling by the `created_at` age guard. Such messages will not be processed and will not be automatically dead-lettered. Ensure `OutboxRuntimeOptions.MaxMessageAge` is greater than the maximum `deliver_at` offset used in your application (e.g., if scheduling up to 7 days ahead, set `MaxMessageAge ≥ 8 days`). Ordering with multiple dispatcher instances: When multiple dispatcher instances run concurrently, messages are fetched in `ORDER BY created_at ASC, id ASC` order but can be claimed by different instances via `SKIP LOCKED`, resulting in non-deterministic global ordering. In partitioned table setups, the order guarantee applies within each partition only. For strict global ordering, use a single dispatcher instance with `MaxDegreeOfParallelism = 1`.

  • methodGetMessageAsync
    public async ValueTask<OutboxMessage?> GetMessageAsync(Guid id, CancellationToken cancellationToken = default)

    Retrieves a single outbox message by its unique identifier, regardless of its current state.

    id: Guid
    The unique identifier of the message to retrieve.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: The `OutboxMessage` with the specified `id`, or `null` if no message with that ID exists in the outbox table.

    AUDIT-FIX P1-G — Default Interface Method for operational tooling: Designed for debugging, manual requeue, and administrative UIs that need to inspect a specific message. It is not used in the normal dispatcher hot path. This is a Default Interface Method (DIM): existing implementations automatically inherit the default implementation which throws `NotSupportedException`. Storage engine implementations should override `GetMessageAsync(Guid, CancellationToken)` for efficient single-row lookup. For PostgreSQL, the expected implementation is: `SELECT * FROM outbox.messages WHERE id = @Id LIMIT 1;`

  • methodGetPendingCountAsync
    public async ValueTask<long> GetPendingCountAsync(CancellationToken cancellationToken = default)

    Retrieves the approximate count of messages awaiting processing.

    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the approximate pending message count.

    Includes messages in the Pending (0) or Failed (3) states for metrics and monitoring.

  • methodInsertAsync
    public async ValueTask InsertAsync(OutboxMessage record, IOutboxTransactionContext transaction, CancellationToken cancellationToken = default)

    Inserts a single message into the outbox table atomically within the specified transaction.

    record: OutboxMessage
    The message to insert into the outbox.
    transaction: IOutboxTransactionContext
    The context representing the active database transaction.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • methodInsertBatchAsync
    public async ValueTask InsertBatchAsync(ReadOnlyMemory<OutboxMessage> records, IOutboxTransactionContext transaction, CancellationToken cancellationToken = default)

    Inserts a batch of messages into the outbox table in a single round-trip.

    records: ReadOnlyMemory<OutboxMessage>
    The batch of messages to insert.
    transaction: IOutboxTransactionContext
    The context representing the active database transaction.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Implementations should use bulk insert mechanisms (e.g., COPY, UNNEST, or table-valued parameters). If native bulk insert is unavailable, implementations fall back to individual inserts.

  • methodMarkAsDispatchedAsync
    public async ValueTask MarkAsDispatchedAsync(IReadOnlyList<OutboxMessage> messages, CancellationToken cancellationToken = default)

    Atomically marks the specified messages as successfully dispatched.

    messages: IReadOnlyList<OutboxMessage>
    The collection of messages to mark as dispatched.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • methodMarkAsFailedAsync
    public async ValueTask MarkAsFailedAsync(IReadOnlyList<OutboxMessage> messages, string error, bool isDeadLetter = false, CancellationToken cancellationToken = default)

    Marks the specified messages as failed, updating their error details and retry counts.

    messages: IReadOnlyList<OutboxMessage>
    The collection of messages that failed to process.
    error: string
    The error message or exception details causing the failure.
    isDeadLetter: bool
    `true` to mark the messages as permanently failed (dead letter); otherwise, `false`.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Is typically invoked by `Retry.RetryDispatcherInterceptor` when publishing fails. If the maximum retry attempts are exhausted, the message may be marked as a dead letter. Security Warning: The `error` parameter may contain sensitive information (such as connection strings in stack traces). Ensure exceptions are sanitized in production environments before they are persisted, to prevent leaking sensitive data.

  • methodPurgeDispatchedMessagesAsync
    public async ValueTask<int> PurgeDispatchedMessagesAsync(DateTimeOffset cutoff, int batchSize = 1000, CancellationToken cancellationToken = default)

    Purges dispatched messages that were processed prior to the specified cutoff timestamp. Used by `Hosting.OutboxCleanupService` when `DeleteOnDispatch = false`.

    cutoff: DateTimeOffset
    The cutoff timestamp; messages dispatched prior to this time will be deleted.
    batchSize: int
    The maximum number of rows to delete in a single batch.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation, returning the number of purged rows.

  • methodReclaimStaleMessagesAsync
    public async ValueTask<int> ReclaimStaleMessagesAsync(TimeSpan staleTimeout, CancellationToken cancellationToken = default)

    Reclaims messages that have remained in the InFlight state longer than the specified timeout.

    staleTimeout: TimeSpan
    The duration after which an InFlight message is considered abandoned.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the number of messages reclaimed.

    This mechanism prevents message loss if a dispatcher crashes after claiming a batch (transitioning from state 0 to 1) but before marking it as dispatched. Implementations must atomically reset these messages to the Pending state (0) if their last updated time is older than the current UTC time minus the stale timeout.

class

MongoDbTransactionContext

Ensamblado: EricksonLopez.Outbox.Storage.MongoDb
public sealed class MongoDbTransactionContext : IOutboxTransactionContext, IAsyncDisposable, IDisposable
Implementa: IAsyncDisposable, IDisposable, IOutboxTransactionContext

Provides a wrapper around a MongoDB `IClientSessionHandle` as an `IOutboxTransactionContext`.

Miembros (8)

  • constructorMongoDbTransactionContext
    public MongoDbTransactionContext(IClientSessionHandle session)

    Initializes a new instance of the `MongoDbTransactionContext` class.

    session: IClientSessionHandle
    The MongoDB client session handle.

    Exceptions: ArgumentNullException: `session` is `null`

  • methodCommitAsync
    public ValueTask CommitAsync(CancellationToken cancellationToken = default)

    Commits the active MongoDB transaction asynchronously.

    cancellationToken: CancellationToken
    A token that may be used to cancel the commit operation.

    Retorna: A value task representing the asynchronous commit operation.

  • methodDispose
    public void Dispose()

    Inherits documentation from base type or interface.

  • methodDisposeAsync
    public ValueTask DisposeAsync()

    Inherits documentation from base type or interface.

  • methodRollbackAsync
    public ValueTask RollbackAsync(CancellationToken cancellationToken = default)

    Aborts the active MongoDB transaction asynchronously.

    cancellationToken: CancellationToken
    A token that may be used to cancel the rollback operation.

    Retorna: A value task representing the asynchronous abort operation.

  • propertyConnection
    public object? Connection { get; }

    Gets the underlying connection object, or `null` if no connection is associated.

  • propertySession
    public IClientSessionHandle Session { get; }

    Gets the underlying MongoDB client session.

  • propertyTransaction
    public object Transaction { get; }

    Gets the underlying transaction object as an untyped reference.

EricksonLopez.Outbox.Storage.MySql#

4
class

MySqlDeadLetterRepository

Ensamblado: EricksonLopez.Outbox.Storage.MySql
public sealed class MySqlDeadLetterRepository : IDeadLetterRepository
Implementa: IDeadLetterRepository

Provides a MySQL implementation of `IDeadLetterRepository`.

Miembros (6)

  • constructorMySqlDeadLetterRepository
    public MySqlDeadLetterRepository(Func<IDbConnection> connectionFactory, IOptionsMonitor<OutboxRuntimeOptions> options)

    Initializes a new instance of the `MySqlDeadLetterRepository` class.

    connectionFactory: Func<IDbConnection>
    The factory that creates MySQL connections.
    options: IOptionsMonitor<OutboxRuntimeOptions>
    The outbox runtime options.

    Exceptions: ArgumentNullException: `connectionFactory` or `options` is `null`

  • methodDeleteAsync
    public async ValueTask DeleteAsync(Guid id, CancellationToken cancellationToken = default)

    Deletes a dead-lettered message by its unique identifier.

    id: Guid
    The unique identifier of the dead-lettered message to delete.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • methodGetAsync
    public async ValueTask<IReadOnlyList<DeadLetterMessage>> GetAsync(int limit = 100, DateTimeOffset? after = null, CancellationToken cancellationToken = default)

    Retrieves a page of dead-lettered messages for inspection or replay.

    limit: int
    The maximum number of records to return.
    after: DateTimeOffset?
    The cursor indicating to return records dead-lettered after this timestamp. Pass `DateTimeOffset.MinValue` for the first page.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the retrieved page of dead-lettered messages.

  • methodInsertAsync
    public async ValueTask InsertAsync(DeadLetterMessage message, IOutboxTransactionContext? transaction = default, CancellationToken cancellationToken = default)

    Persists a dead-lettered message.

    message: DeadLetterMessage
    The dead-lettered message to persist.
    transaction: IOutboxTransactionContext?
    The optional transaction context. If `null`, the repository must open its own connection and auto-commit the insert.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Called by the Dispatcher after a message has exhausted its `Retry.RetryPolicy`.

  • methodPurgeAsync
    public async ValueTask PurgeAsync(DateTimeOffset olderThan, CancellationToken cancellationToken = default)

    Purges all dead-lettered messages older than the specified timestamp.

    olderThan: DateTimeOffset
    The timestamp threshold; messages older than this value will be purged.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • propertyIsFirstPartyImplementation
    public bool IsFirstPartyImplementation { get; }

    Gets a value indicating whether this is a first-party (built-in) implementation.

    Used by `OutboxStartupValidator` to warn operators when a third-party `IDeadLetterRepository` is registered, reminding them to verify that their implementation correctly handles `transaction = null` (auto-commit mode). All first-party storage engine implementations override this to return `true`. Third-party implementations that do not override this will return `false`, triggering the startup advisory log message. This is a Zero-Reflection pattern: no `GetType().Name`, no string comparisons, no assembly scanning. The check is a simple virtual dispatch.

class

MySqlIdempotencyRepository

Ensamblado: EricksonLopez.Outbox.Storage.MySql
public sealed class MySqlIdempotencyRepository : IIdempotencyRepository
Implementa: IIdempotencyRepository

Provides a MySQL implementation of `IIdempotencyRepository`.

Miembros (3)

  • constructorMySqlIdempotencyRepository
    public MySqlIdempotencyRepository(Func<IDbConnection> connectionFactory, IOptionsMonitor<OutboxRuntimeOptions> options)

    Initializes a new instance of the `MySqlIdempotencyRepository` class.

    connectionFactory: Func<IDbConnection>
    The factory that creates MySQL connections.
    options: IOptionsMonitor<OutboxRuntimeOptions>
    The outbox runtime options.

    Exceptions: ArgumentNullException: `connectionFactory` or `options` is `null`

  • methodPurgeExpiredRecordsAsync
    public async ValueTask PurgeExpiredRecordsAsync(DateTimeOffset olderThan, CancellationToken cancellationToken = default)

    Purges idempotency records older than the specified timestamp.

    olderThan: DateTimeOffset
    The timestamp threshold; records older than this value will be purged.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Called periodically by `InboxCleanupService` to prevent table bloat.

  • methodTryInsertAsync
    public async ValueTask<bool> TryInsertAsync(IdempotencyRecord record, IOutboxTransactionContext? transaction = default, CancellationToken cancellationToken = default)

    Attempts to insert an idempotency record.

    record: IdempotencyRecord
    The idempotency record to insert.
    transaction: IOutboxTransactionContext?
    The optional transaction context.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result is `true` if the record was inserted; otherwise, `false` if the record already exists (duplicate).

class

MySqlOutboxRepository

Ensamblado: EricksonLopez.Outbox.Storage.MySql
public sealed class MySqlOutboxRepository : IOutboxRepository
Implementa: IOutboxRepository

Provides a MySQL implementation of `IOutboxRepository`.

Miembros (9)

  • constructorMySqlOutboxRepository
    public MySqlOutboxRepository(Func<IDbConnection> connectionFactory, IOptions<OutboxRuntimeOptions>? options = null)

    Initializes a new instance of the `MySqlOutboxRepository` class.

    connectionFactory: Func<IDbConnection>
    The factory that creates MySQL connections.
    options: IOptions<OutboxRuntimeOptions>?
    The runtime options containing thresholds and configurations.

    Exceptions: ArgumentNullException: `connectionFactory` is `null`

  • methodFetchPendingAsync
    public async ValueTask<IReadOnlyList<OutboxMessage>> FetchPendingAsync(int batchSize, CancellationToken cancellationToken = default)

    Retrieves a batch of pending messages ready for delivery.

    batchSize: int
    The maximum number of messages to retrieve.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the batch of messages retrieved.

    The method fetches up to the specified batch size of messages that are in the Pending state (0) and whose delivery time is less than or equal to the current UTC time. Implementations guarantee safe concurrent polling by using SKIP LOCKED or equivalent semantics, atomically transitioning the fetched messages to the InFlight state (1). Scheduling edge case — `deliver_at` vs `MaxMessageAge`: Messages stored with a future `deliver_at` timestamp that exceeds `MaxMessageAge` will be silently excluded from polling by the `created_at` age guard. Such messages will not be processed and will not be automatically dead-lettered. Ensure `OutboxRuntimeOptions.MaxMessageAge` is greater than the maximum `deliver_at` offset used in your application (e.g., if scheduling up to 7 days ahead, set `MaxMessageAge ≥ 8 days`). Ordering with multiple dispatcher instances: When multiple dispatcher instances run concurrently, messages are fetched in `ORDER BY created_at ASC, id ASC` order but can be claimed by different instances via `SKIP LOCKED`, resulting in non-deterministic global ordering. In partitioned table setups, the order guarantee applies within each partition only. For strict global ordering, use a single dispatcher instance with `MaxDegreeOfParallelism = 1`.

  • methodGetPendingCountAsync
    public async ValueTask<long> GetPendingCountAsync(CancellationToken cancellationToken = default)

    Retrieves the approximate count of messages awaiting processing.

    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the approximate pending message count.

    Includes messages in the Pending (0) or Failed (3) states for metrics and monitoring.

  • methodInsertAsync
    public async ValueTask InsertAsync(OutboxMessage record, IOutboxTransactionContext transaction, CancellationToken cancellationToken = default)

    Inserts a single message into the outbox table atomically within the specified transaction.

    record: OutboxMessage
    The message to insert into the outbox.
    transaction: IOutboxTransactionContext
    The context representing the active database transaction.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • methodInsertBatchAsync
    public async ValueTask InsertBatchAsync(ReadOnlyMemory<OutboxMessage> records, IOutboxTransactionContext transaction, CancellationToken cancellationToken = default)

    Inserts a batch of messages into the outbox table in a single round-trip.

    records: ReadOnlyMemory<OutboxMessage>
    The batch of messages to insert.
    transaction: IOutboxTransactionContext
    The context representing the active database transaction.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Implementations should use bulk insert mechanisms (e.g., COPY, UNNEST, or table-valued parameters). If native bulk insert is unavailable, implementations fall back to individual inserts.

  • methodMarkAsDispatchedAsync
    public async ValueTask MarkAsDispatchedAsync(IReadOnlyList<OutboxMessage> messages, CancellationToken cancellationToken = default)

    Atomically marks the specified messages as successfully dispatched.

    messages: IReadOnlyList<OutboxMessage>
    The collection of messages to mark as dispatched.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • methodMarkAsFailedAsync
    public async ValueTask MarkAsFailedAsync(IReadOnlyList<OutboxMessage> messages, string error, bool isDeadLetter = false, CancellationToken cancellationToken = default)

    Marks the specified messages as failed, updating their error details and retry counts.

    messages: IReadOnlyList<OutboxMessage>
    The collection of messages that failed to process.
    error: string
    The error message or exception details causing the failure.
    isDeadLetter: bool
    `true` to mark the messages as permanently failed (dead letter); otherwise, `false`.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Is typically invoked by `Retry.RetryDispatcherInterceptor` when publishing fails. If the maximum retry attempts are exhausted, the message may be marked as a dead letter. Security Warning: The `error` parameter may contain sensitive information (such as connection strings in stack traces). Ensure exceptions are sanitized in production environments before they are persisted, to prevent leaking sensitive data.

  • methodPurgeDispatchedMessagesAsync
    public async ValueTask<int> PurgeDispatchedMessagesAsync(DateTimeOffset cutoff, int batchSize = 1000, CancellationToken cancellationToken = default)

    Purges dispatched messages that were processed prior to the specified cutoff timestamp. Used by `Hosting.OutboxCleanupService` when `DeleteOnDispatch = false`.

    cutoff: DateTimeOffset
    The cutoff timestamp; messages dispatched prior to this time will be deleted.
    batchSize: int
    The maximum number of rows to delete in a single batch.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation, returning the number of purged rows.

  • methodReclaimStaleMessagesAsync
    public async ValueTask<int> ReclaimStaleMessagesAsync(TimeSpan staleTimeout, CancellationToken cancellationToken = default)

    Reclaims messages that have remained in the InFlight state longer than the specified timeout.

    staleTimeout: TimeSpan
    The duration after which an InFlight message is considered abandoned.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the number of messages reclaimed.

    This mechanism prevents message loss if a dispatcher crashes after claiming a batch (transitioning from state 0 to 1) but before marking it as dispatched. Implementations must atomically reset these messages to the Pending state (0) if their last updated time is older than the current UTC time minus the stale timeout.

class

MySqlOutboxSetup

Ensamblado: EricksonLopez.Outbox.Storage.MySql
public static class MySqlOutboxSetup

Provides extension methods for configuring MySQL outbox storage.

Miembros (1)

  • methodUseMySql
    public static OutboxOptions UseMySql(this OutboxOptions options, Func<IServiceProvider, MySqlConnection> connectionFactory)

    Configures the outbox to use MySQL as the storage engine using the provided connection factory.

    options: this OutboxOptions
    The outbox options being configured.
    connectionFactory: Func<IServiceProvider, MySqlConnection>
    A factory delegate to provide a `MySqlConnection` based on the `IServiceProvider`.

    Retorna: The original `OutboxOptions` for method chaining.

    Exceptions: ArgumentNullException: `options` or `connectionFactory` is `null`

EricksonLopez.Outbox.Storage.Oracle#

4
class

OracleDeadLetterRepository

Ensamblado: EricksonLopez.Outbox.Storage.Oracle
public sealed class OracleDeadLetterRepository : IDeadLetterRepository
Implementa: IDeadLetterRepository

Provides an Oracle implementation of `IDeadLetterRepository`.

Miembros (6)

  • constructorOracleDeadLetterRepository
    public OracleDeadLetterRepository(Func<IDbConnection> connectionFactory, IOptionsMonitor<OutboxRuntimeOptions> options)

    Initializes a new instance of the `OracleDeadLetterRepository` class.

    connectionFactory: Func<IDbConnection>
    The factory that creates Oracle connections.
    options: IOptionsMonitor<OutboxRuntimeOptions>
    The outbox runtime options.

    Exceptions: ArgumentNullException: `connectionFactory` or `options` is `null`

  • methodDeleteAsync
    public async ValueTask DeleteAsync(Guid id, CancellationToken cancellationToken = default)

    Deletes a dead-lettered message by its unique identifier.

    id: Guid
    The unique identifier of the dead-lettered message to delete.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • methodGetAsync
    public async ValueTask<IReadOnlyList<DeadLetterMessage>> GetAsync(int limit = 100, DateTimeOffset? after = null, CancellationToken cancellationToken = default)

    Retrieves a page of dead-lettered messages for inspection or replay.

    limit: int
    The maximum number of records to return.
    after: DateTimeOffset?
    The cursor indicating to return records dead-lettered after this timestamp. Pass `DateTimeOffset.MinValue` for the first page.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the retrieved page of dead-lettered messages.

  • methodInsertAsync
    public async ValueTask InsertAsync(DeadLetterMessage message, IOutboxTransactionContext? transaction = default, CancellationToken cancellationToken = default)

    Persists a dead-lettered message.

    message: DeadLetterMessage
    The dead-lettered message to persist.
    transaction: IOutboxTransactionContext?
    The optional transaction context. If `null`, the repository must open its own connection and auto-commit the insert.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Called by the Dispatcher after a message has exhausted its `Retry.RetryPolicy`.

  • methodPurgeAsync
    public async ValueTask PurgeAsync(DateTimeOffset olderThan, CancellationToken cancellationToken = default)

    Purges all dead-lettered messages older than the specified timestamp.

    olderThan: DateTimeOffset
    The timestamp threshold; messages older than this value will be purged.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • propertyIsFirstPartyImplementation
    public bool IsFirstPartyImplementation { get; }

    Gets a value indicating whether this is a first-party (built-in) implementation.

    Used by `OutboxStartupValidator` to warn operators when a third-party `IDeadLetterRepository` is registered, reminding them to verify that their implementation correctly handles `transaction = null` (auto-commit mode). All first-party storage engine implementations override this to return `true`. Third-party implementations that do not override this will return `false`, triggering the startup advisory log message. This is a Zero-Reflection pattern: no `GetType().Name`, no string comparisons, no assembly scanning. The check is a simple virtual dispatch.

class

OracleIdempotencyRepository

Ensamblado: EricksonLopez.Outbox.Storage.Oracle
public sealed class OracleIdempotencyRepository : IIdempotencyRepository
Implementa: IIdempotencyRepository

Provides an Oracle implementation of `IIdempotencyRepository`.

Miembros (3)

  • constructorOracleIdempotencyRepository
    public OracleIdempotencyRepository(Func<IDbConnection> connectionFactory, IOptionsMonitor<OutboxRuntimeOptions> options)

    Initializes a new instance of the `OracleIdempotencyRepository` class.

    connectionFactory: Func<IDbConnection>
    The factory that creates Oracle connections.
    options: IOptionsMonitor<OutboxRuntimeOptions>
    The outbox runtime options.

    Exceptions: ArgumentNullException: `connectionFactory` or `options` is `null`

  • methodPurgeExpiredRecordsAsync
    public async ValueTask PurgeExpiredRecordsAsync(DateTimeOffset olderThan, CancellationToken cancellationToken = default)

    Purges idempotency records older than the specified timestamp.

    olderThan: DateTimeOffset
    The timestamp threshold; records older than this value will be purged.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Called periodically by `InboxCleanupService` to prevent table bloat.

  • methodTryInsertAsync
    public async ValueTask<bool> TryInsertAsync(IdempotencyRecord record, IOutboxTransactionContext? transaction = default, CancellationToken cancellationToken = default)

    Attempts to insert an idempotency record.

    record: IdempotencyRecord
    The idempotency record to insert.
    transaction: IOutboxTransactionContext?
    The optional transaction context.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result is `true` if the record was inserted; otherwise, `false` if the record already exists (duplicate).

class

OracleOutboxRepository

Ensamblado: EricksonLopez.Outbox.Storage.Oracle
public sealed class OracleOutboxRepository : IOutboxRepository
Implementa: IOutboxRepository

Provides an Oracle implementation of `IOutboxRepository`.

Miembros (9)

  • constructorOracleOutboxRepository
    public OracleOutboxRepository(Func<IDbConnection> connectionFactory, IOptions<OutboxRuntimeOptions>? options = null)

    Initializes a new instance of the `OracleOutboxRepository` class.

    connectionFactory: Func<IDbConnection>
    The factory that creates Oracle connections.
    options: IOptions<OutboxRuntimeOptions>?
    The runtime options containing thresholds and configurations.

    Exceptions: ArgumentNullException: `connectionFactory` is `null`

  • methodFetchPendingAsync
    public async ValueTask<IReadOnlyList<OutboxMessage>> FetchPendingAsync(int batchSize, CancellationToken cancellationToken = default)

    Retrieves a batch of pending messages ready for delivery.

    batchSize: int
    The maximum number of messages to retrieve.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the batch of messages retrieved.

    The method fetches up to the specified batch size of messages that are in the Pending state (0) and whose delivery time is less than or equal to the current UTC time. Implementations guarantee safe concurrent polling by using SKIP LOCKED or equivalent semantics, atomically transitioning the fetched messages to the InFlight state (1). Scheduling edge case — `deliver_at` vs `MaxMessageAge`: Messages stored with a future `deliver_at` timestamp that exceeds `MaxMessageAge` will be silently excluded from polling by the `created_at` age guard. Such messages will not be processed and will not be automatically dead-lettered. Ensure `OutboxRuntimeOptions.MaxMessageAge` is greater than the maximum `deliver_at` offset used in your application (e.g., if scheduling up to 7 days ahead, set `MaxMessageAge ≥ 8 days`). Ordering with multiple dispatcher instances: When multiple dispatcher instances run concurrently, messages are fetched in `ORDER BY created_at ASC, id ASC` order but can be claimed by different instances via `SKIP LOCKED`, resulting in non-deterministic global ordering. In partitioned table setups, the order guarantee applies within each partition only. For strict global ordering, use a single dispatcher instance with `MaxDegreeOfParallelism = 1`.

  • methodGetPendingCountAsync
    public async ValueTask<long> GetPendingCountAsync(CancellationToken cancellationToken = default)

    Retrieves the approximate count of messages awaiting processing.

    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the approximate pending message count.

    Includes messages in the Pending (0) or Failed (3) states for metrics and monitoring.

  • methodInsertAsync
    public async ValueTask InsertAsync(OutboxMessage record, IOutboxTransactionContext transaction, CancellationToken cancellationToken = default)

    Inserts a single message into the outbox table atomically within the specified transaction.

    record: OutboxMessage
    The message to insert into the outbox.
    transaction: IOutboxTransactionContext
    The context representing the active database transaction.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • methodInsertBatchAsync
    public async ValueTask InsertBatchAsync(ReadOnlyMemory<OutboxMessage> records, IOutboxTransactionContext transaction, CancellationToken cancellationToken = default)

    Inserts a batch of messages into the outbox table in a single round-trip.

    records: ReadOnlyMemory<OutboxMessage>
    The batch of messages to insert.
    transaction: IOutboxTransactionContext
    The context representing the active database transaction.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Implementations should use bulk insert mechanisms (e.g., COPY, UNNEST, or table-valued parameters). If native bulk insert is unavailable, implementations fall back to individual inserts.

  • methodMarkAsDispatchedAsync
    public async ValueTask MarkAsDispatchedAsync(IReadOnlyList<OutboxMessage> messages, CancellationToken cancellationToken = default)

    Atomically marks the specified messages as successfully dispatched.

    messages: IReadOnlyList<OutboxMessage>
    The collection of messages to mark as dispatched.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • methodMarkAsFailedAsync
    public async ValueTask MarkAsFailedAsync(IReadOnlyList<OutboxMessage> messages, string error, bool isDeadLetter = false, CancellationToken cancellationToken = default)

    Marks the specified messages as failed, updating their error details and retry counts.

    messages: IReadOnlyList<OutboxMessage>
    The collection of messages that failed to process.
    error: string
    The error message or exception details causing the failure.
    isDeadLetter: bool
    `true` to mark the messages as permanently failed (dead letter); otherwise, `false`.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Is typically invoked by `Retry.RetryDispatcherInterceptor` when publishing fails. If the maximum retry attempts are exhausted, the message may be marked as a dead letter. Security Warning: The `error` parameter may contain sensitive information (such as connection strings in stack traces). Ensure exceptions are sanitized in production environments before they are persisted, to prevent leaking sensitive data.

  • methodPurgeDispatchedMessagesAsync
    public async ValueTask<int> PurgeDispatchedMessagesAsync(DateTimeOffset cutoff, int batchSize = 1000, CancellationToken cancellationToken = default)

    Purges dispatched messages that were processed prior to the specified cutoff timestamp. Used by `Hosting.OutboxCleanupService` when `DeleteOnDispatch = false`.

    cutoff: DateTimeOffset
    The cutoff timestamp; messages dispatched prior to this time will be deleted.
    batchSize: int
    The maximum number of rows to delete in a single batch.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation, returning the number of purged rows.

  • methodReclaimStaleMessagesAsync
    public async ValueTask<int> ReclaimStaleMessagesAsync(TimeSpan staleTimeout, CancellationToken cancellationToken = default)

    Reclaims messages that have remained in the InFlight state longer than the specified timeout.

    staleTimeout: TimeSpan
    The duration after which an InFlight message is considered abandoned.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the number of messages reclaimed.

    This mechanism prevents message loss if a dispatcher crashes after claiming a batch (transitioning from state 0 to 1) but before marking it as dispatched. Implementations must atomically reset these messages to the Pending state (0) if their last updated time is older than the current UTC time minus the stale timeout.

class

OracleOutboxSetup

Ensamblado: EricksonLopez.Outbox.Storage.Oracle
public static class OracleOutboxSetup

Provides extension methods for configuring Oracle outbox storage.

Miembros (1)

  • methodUseOracle
    public static OutboxOptions UseOracle(this OutboxOptions options, Func<IServiceProvider, OracleConnection> connectionFactory)

    Configures the outbox to use Oracle as the storage engine using the provided connection factory.

    options: this OutboxOptions
    The outbox options being configured.
    connectionFactory: Func<IServiceProvider, OracleConnection>
    A factory delegate to provide an `OracleConnection` based on the `IServiceProvider`.

    Retorna: The original `OutboxOptions` for method chaining.

    Exceptions: ArgumentNullException: `options` or `connectionFactory` is `null`

EricksonLopez.Outbox.Storage.PostgreSql#

12
interface

IPostgreSqlDeadLetterRepository

Ensamblado: EricksonLopez.Outbox.Storage.PostgreSql
public interface IPostgreSqlDeadLetterRepository : IDeadLetterRepository
Implementa: IDeadLetterRepository

Extends `IDeadLetterRepository` with PostgreSQL-specific atomic transfer and dead-letter handling capabilities.

Miembros (2)

  • methodHandleFailedDeliveryAsync
    ValueTask<bool> HandleFailedDeliveryAsync(Guid messageId, int currentRetryCount, string reason, string? lastError, IOutboxTransactionContext? transaction = default, CancellationToken cancellationToken = default)

    Evaluates delivery failure against the configured maximum delivery retries. If retries exceed the threshold, atomically moves the message to the dead-letter table; otherwise updates the retry counter.

    messageId: Guid
    The identifier of the message that failed delivery.
    currentRetryCount: int
    The current retry count prior to this failure.
    reason: string
    The reason for failure.
    lastError: string?
    The error description.
    transaction: IOutboxTransactionContext?
    The optional transaction context.
    cancellationToken: CancellationToken
    A token to cancel the operation.

    Retorna: `true` if the message was moved to dead-letter queue; `false` if scheduled for retry.

  • methodMoveToDeadLetterAsync
    ValueTask<bool> MoveToDeadLetterAsync(Guid messageId, string reason, string? lastError, int retryCount, IOutboxTransactionContext? transaction = default, CancellationToken cancellationToken = default)

    Atomically moves a failed message from the outbox messages table to the dead-letter table in a single atomic database operation.

    messageId: Guid
    The identifier of the message to move.
    reason: string
    The reason why the message was dead-lettered.
    lastError: string?
    The last error message or exception details.
    retryCount: int
    The current retry count of the message.
    transaction: IOutboxTransactionContext?
    The optional transaction context in which to enlist.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: `true` if the message was found and moved; `false` if not found.

interface

IPostgreSqlSessionContext

Ensamblado: EricksonLopez.Outbox.Storage.PostgreSql
public interface IPostgreSqlSessionContext

Defines a contract for configuring PostgreSQL session context parameters (such as tenant/company context) for Row Level Security (RLS) and multi-tenant isolation.

Miembros (5)

  • methodApplyTenantSessionContextAsync
    ValueTask ApplyTenantSessionContextAsync(IDbConnection connection, string? tenantId, bool? isLocal = null, IDbTransaction? transaction = null, CancellationToken cancellationToken = default)

    Applies or resets the primary and any additional configured tenant session context parameters on the specified database connection and optional transaction.

    connection: IDbConnection
    The database connection.
    tenantId: string?
    The tenant or company identifier value, or `null` to clear.
    isLocal: bool?
    Whether the setting is local to the current transaction. If null, uses the configured default.
    transaction: IDbTransaction?
    The optional database transaction.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation.

  • methodApplyTenantSessionContextAsync
    ValueTask ApplyTenantSessionContextAsync(NpgsqlConnection connection, string? tenantId, bool? isLocal = null, NpgsqlTransaction? transaction = null, CancellationToken cancellationToken = default)

    Applies or resets the primary and any additional configured tenant session context parameters on the specified PostgreSQL connection and optional transaction. When `tenantId` is `null` or whitespace, the session context parameters are reset to empty strings.

    connection: NpgsqlConnection
    The PostgreSQL connection.
    tenantId: string?
    The tenant or company identifier value, or `null` to clear.
    isLocal: bool?
    Whether the setting is local to the current transaction. If null, uses the configured default.
    transaction: NpgsqlTransaction?
    The optional PostgreSQL transaction.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation.

  • methodResetSessionContextAsync
    ValueTask ResetSessionContextAsync(NpgsqlConnection connection, bool? isLocal = null, NpgsqlTransaction? transaction = null, CancellationToken cancellationToken = default)

    Resets the session context parameter on the specified PostgreSQL connection to an empty value.

    connection: NpgsqlConnection
    The PostgreSQL connection.
    isLocal: bool?
    Whether the setting reset is local to the current transaction. If null, uses the configured default.
    transaction: NpgsqlTransaction?
    The optional PostgreSQL transaction.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation.

  • methodSetSessionContextAsync
    ValueTask SetSessionContextAsync(NpgsqlConnection connection, string tenantId, bool? isLocal = null, NpgsqlTransaction? transaction = null, CancellationToken cancellationToken = default)

    Sets the session context parameter on the specified PostgreSQL connection.

    connection: NpgsqlConnection
    The PostgreSQL connection.
    tenantId: string
    The tenant or company identifier value.
    isLocal: bool?
    Whether the setting is local to the current transaction. If null, uses the configured default.
    transaction: NpgsqlTransaction?
    The optional PostgreSQL transaction.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation.

  • methodSetSessionContextAsync
    ValueTask SetSessionContextAsync(string tenantId, bool? isLocal = null, CancellationToken cancellationToken = default)

    Opens a connection from the configured data source and sets the session context parameter.

    tenantId: string
    The tenant or company identifier value.
    isLocal: bool?
    Whether the setting is local to the current transaction. If null, uses the configured default.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation.

class

PostgreSqlDeadLetterRepository

Ensamblado: EricksonLopez.Outbox.Storage.PostgreSql
public sealed class PostgreSqlDeadLetterRepository : IPostgreSqlDeadLetterRepository
Implementa: IPostgreSqlDeadLetterRepository

Provides a PostgreSQL implementation of `IDeadLetterRepository`.

Miembros (9)

  • constructorPostgreSqlDeadLetterRepository
    public PostgreSqlDeadLetterRepository(NpgsqlDataSource dataSource, IOptionsMonitor<OutboxRuntimeOptions> options)

    Initializes a new instance of the `PostgreSqlDeadLetterRepository` class.

    dataSource: NpgsqlDataSource
    The PostgreSQL data source.
    options: IOptionsMonitor<OutboxRuntimeOptions>
    The outbox runtime options.

    Exceptions: ArgumentNullException: `dataSource` or `options` is `null`

  • constructorPostgreSqlDeadLetterRepository
    public PostgreSqlDeadLetterRepository(NpgsqlDataSource dataSource, IOptionsMonitor<OutboxRuntimeOptions> options, IOptions<PostgreSqlStorageOptions>? storageOptions)

    Initializes a new instance of the `PostgreSqlDeadLetterRepository` class with storage options.

    dataSource: NpgsqlDataSource
    The PostgreSQL data source.
    options: IOptionsMonitor<OutboxRuntimeOptions>
    The outbox runtime options.
    storageOptions: IOptions<PostgreSqlStorageOptions>?
    The PostgreSQL storage options.

    Exceptions: ArgumentNullException: `dataSource` or `options` is `null`

  • methodDeleteAsync
    public async ValueTask DeleteAsync(Guid id, CancellationToken cancellationToken = default)

    Inherits documentation from base type or interface.

    id: Guid
    cancellationToken: CancellationToken
  • methodGetAsync
    public async ValueTask<IReadOnlyList<DeadLetterMessage>> GetAsync(int limit = 100, DateTimeOffset? after = null, CancellationToken cancellationToken = default)

    Inherits documentation from base type or interface.

    limit: int
    after: DateTimeOffset?
    cancellationToken: CancellationToken
  • methodHandleFailedDeliveryAsync
    public async ValueTask<bool> HandleFailedDeliveryAsync(Guid messageId, int currentRetryCount, string reason, string? lastError, IOutboxTransactionContext? transaction = default, CancellationToken cancellationToken = default)

    Evaluates delivery failure against the configured maximum delivery retries. If retries exceed the threshold, atomically moves the message to the dead-letter table; otherwise updates the retry counter.

    messageId: Guid
    The identifier of the message that failed delivery.
    currentRetryCount: int
    The current retry count prior to this failure.
    reason: string
    The reason for failure.
    lastError: string?
    The error description.
    transaction: IOutboxTransactionContext?
    The optional transaction context.
    cancellationToken: CancellationToken
    A token to cancel the operation.

    Retorna: `true` if the message was moved to dead-letter queue; `false` if scheduled for retry.

  • methodInsertAsync
    public async ValueTask InsertAsync(DeadLetterMessage message, IOutboxTransactionContext? transaction = default, CancellationToken cancellationToken = default)

    Inherits documentation from base type or interface.

    message: DeadLetterMessage
    transaction: IOutboxTransactionContext?
    cancellationToken: CancellationToken
  • methodMoveToDeadLetterAsync
    public async ValueTask<bool> MoveToDeadLetterAsync(Guid messageId, string reason, string? lastError, int retryCount, IOutboxTransactionContext? transaction = default, CancellationToken cancellationToken = default)

    Atomically moves a failed message from the outbox messages table to the dead-letter table in a single atomic database operation.

    messageId: Guid
    The identifier of the message to move.
    reason: string
    The reason why the message was dead-lettered.
    lastError: string?
    The last error message or exception details.
    retryCount: int
    The current retry count of the message.
    transaction: IOutboxTransactionContext?
    The optional transaction context in which to enlist.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: `true` if the message was found and moved; `false` if not found.

  • methodPurgeAsync
    public async ValueTask PurgeAsync(DateTimeOffset olderThan, CancellationToken cancellationToken = default)

    Inherits documentation from base type or interface.

    olderThan: DateTimeOffset
    cancellationToken: CancellationToken
  • propertyIsFirstPartyImplementation
    public bool IsFirstPartyImplementation { get; }

    Inherits documentation from base type or interface.

class

PostgreSqlIdempotencyRepository

Ensamblado: EricksonLopez.Outbox.Storage.PostgreSql
public sealed class PostgreSqlIdempotencyRepository : IIdempotencyRepository
Implementa: IIdempotencyRepository

Provides a PostgreSQL implementation of `IIdempotencyRepository`.

Miembros (3)

  • constructorPostgreSqlIdempotencyRepository
    public PostgreSqlIdempotencyRepository(NpgsqlDataSource dataSource, IOptionsMonitor<OutboxRuntimeOptions> options)

    Initializes a new instance of the `PostgreSqlIdempotencyRepository` class.

    dataSource: NpgsqlDataSource
    The PostgreSQL data source.
    options: IOptionsMonitor<OutboxRuntimeOptions>
    The outbox runtime options.

    Exceptions: ArgumentNullException: `dataSource` or `options` is `null`

  • methodPurgeExpiredRecordsAsync
    public async ValueTask PurgeExpiredRecordsAsync(DateTimeOffset olderThan, CancellationToken cancellationToken = default)

    Purges idempotency records older than the specified timestamp.

    olderThan: DateTimeOffset
    The timestamp threshold; records older than this value will be purged.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Called periodically by `InboxCleanupService` to prevent table bloat.

  • methodTryInsertAsync
    public async ValueTask<bool> TryInsertAsync(IdempotencyRecord record, IOutboxTransactionContext? transaction = default, CancellationToken cancellationToken = default)

    Attempts to insert an idempotency record.

    record: IdempotencyRecord
    The idempotency record to insert.
    transaction: IOutboxTransactionContext?
    The optional transaction context.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result is `true` if the record was inserted; otherwise, `false` if the record already exists (duplicate).

class

PostgreSqlOutboxRepository

Ensamblado: EricksonLopez.Outbox.Storage.PostgreSql
public sealed partial class PostgreSqlOutboxRepository : IOutboxRepository
Implementa: IOutboxRepository

Provides a PostgreSQL-specific implementation of `IOutboxRepository` supporting `FOR UPDATE SKIP LOCKED`, configurable lease columns (`owner_id` / `locked_by` + `locked_until`), `SECURITY DEFINER` multi-tenant Row-Level Security (RLS) worker functions, and transaction-scoped GUC callbacks.

Miembros (16)

  • constructorPostgreSqlOutboxRepository
    public PostgreSqlOutboxRepository(NpgsqlDataSource dataSource, IOptions<OutboxRuntimeOptions>? options = null)

    Initializes a new instance of the `PostgreSqlOutboxRepository` class.

    dataSource: NpgsqlDataSource
    options: IOptions<OutboxRuntimeOptions>?
  • constructorPostgreSqlOutboxRepository
    public PostgreSqlOutboxRepository(NpgsqlDataSource dataSource, IOptions<OutboxRuntimeOptions>? options, IOptions<PostgreSqlStorageOptions>? postgreSqlOptions)

    Initializes a new instance of the `PostgreSqlOutboxRepository` class with storage options.

    dataSource: NpgsqlDataSource
    options: IOptions<OutboxRuntimeOptions>?
    postgreSqlOptions: IOptions<PostgreSqlStorageOptions>?
  • methodApplyTenantSessionContextAsync
    public static ValueTask ApplyTenantSessionContextAsync(IDbConnection connection, string? tenantId, bool isLocal = true, IDbTransaction? transaction = null, PostgreSqlStorageOptions? options = null, CancellationToken cancellationToken = default)

    Applies or resets the primary and any additional configured tenant session context parameters on the specified database connection and optional transaction using PostgreSQL `set_config`.

    connection: IDbConnection
    tenantId: string?
    isLocal: bool
    transaction: IDbTransaction?
    options: PostgreSqlStorageOptions?
    cancellationToken: CancellationToken
  • methodFetchPendingAsync
    public async ValueTask<IReadOnlyList<OutboxMessage>> FetchPendingAsync(int batchSize, CancellationToken cancellationToken = default)

    Retrieves a batch of pending messages ready for delivery.

    batchSize: int
    The maximum number of messages to retrieve.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the batch of messages retrieved.

    The method fetches up to the specified batch size of messages that are in the Pending state (0) and whose delivery time is less than or equal to the current UTC time. Implementations guarantee safe concurrent polling by using SKIP LOCKED or equivalent semantics, atomically transitioning the fetched messages to the InFlight state (1). Scheduling edge case — `deliver_at` vs `MaxMessageAge`: Messages stored with a future `deliver_at` timestamp that exceeds `MaxMessageAge` will be silently excluded from polling by the `created_at` age guard. Such messages will not be processed and will not be automatically dead-lettered. Ensure `OutboxRuntimeOptions.MaxMessageAge` is greater than the maximum `deliver_at` offset used in your application (e.g., if scheduling up to 7 days ahead, set `MaxMessageAge ≥ 8 days`). Ordering with multiple dispatcher instances: When multiple dispatcher instances run concurrently, messages are fetched in `ORDER BY created_at ASC, id ASC` order but can be claimed by different instances via `SKIP LOCKED`, resulting in non-deterministic global ordering. In partitioned table setups, the order guarantee applies within each partition only. For strict global ordering, use a single dispatcher instance with `MaxDegreeOfParallelism = 1`.

  • methodFetchPendingWithTenantContextAsync
    public async ValueTask<IReadOnlyList<OutboxMessage>> FetchPendingWithTenantContextAsync(int batchSize, string tenantId, CancellationToken cancellationToken = default)

    Fetches pending messages for processing while setting the PostgreSQL session context inside a transaction when `PostgreSqlStorageOptions.SessionContextIsLocal` is enabled, enforcing Row-Level Security (RLS) policies safely.

    batchSize: int
    tenantId: string
    cancellationToken: CancellationToken
  • methodGetMessageAsync
    public async ValueTask<OutboxMessage?> GetMessageAsync(Guid id, CancellationToken cancellationToken = default)

    Retrieves a single outbox message by its unique identifier, regardless of its current state.

    id: Guid
    The unique identifier of the message to retrieve.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: The `OutboxMessage` with the specified `id`, or `null` if no message with that ID exists in the outbox table.

    AUDIT-FIX P1-G — Default Interface Method for operational tooling: Designed for debugging, manual requeue, and administrative UIs that need to inspect a specific message. It is not used in the normal dispatcher hot path. This is a Default Interface Method (DIM): existing implementations automatically inherit the default implementation which throws `NotSupportedException`. Storage engine implementations should override `GetMessageAsync(Guid, CancellationToken)` for efficient single-row lookup. For PostgreSQL, the expected implementation is: `SELECT * FROM outbox.messages WHERE id = @Id LIMIT 1;`

  • methodGetMessageAsync
    public async ValueTask<OutboxMessage?> GetMessageAsync(Guid id, DateTimeOffset? createdAtHint, CancellationToken cancellationToken = default)

    Retrieves a single outbox message by its unique identifier, with an optional `created_at` hint to enable partition pruning in range-partitioned table deployments.

    id: Guid
    The unique identifier of the message to retrieve.
    createdAtHint: DateTimeOffset?
    An optional `DateTimeOffset` hint that, when provided, enables partition pruning in range-partitioned table deployments. Must match the exact `created_at` value stored for the message. Pass `null` to fall back to a full-table scan.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: The `OutboxMessage` with the specified `id`, or `null` if no message with that ID exists in the outbox table.

    S-01 AUDIT FIX — Partition pruning hint: In range-partitioned deployments (e.g., PostgreSQL with PARTITION BY RANGE on `created_at`), a lookup by `id` alone requires scanning all partition children because `id` is not the partition key. Providing `createdAtHint` adds an additional `AND created_at = @CreatedAt` predicate, allowing the PostgreSQL query planner to prune to the single target partition and perform an index seek instead of a full-table scan. When to use: Administrative UIs and operational tools that already have the full `OutboxMessage.CreatedAt` value (e.g., from a previous list query or from the original `StoreAsync` response) should use this overload for significantly faster lookup. Default implementation: Delegates to `GetMessageAsync(Guid, CancellationToken)` (ignoring the hint) for backward compatibility. Partition-aware storage engines should override `GetMessageAsync(Guid, DateTimeOffset?, CancellationToken)` to enable partition pruning.

  • methodGetPendingCountAsync
    public async ValueTask<long> GetPendingCountAsync(CancellationToken cancellationToken = default)

    Retrieves the approximate count of messages awaiting processing.

    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the approximate pending message count.

    Includes messages in the Pending (0) or Failed (3) states for metrics and monitoring.

  • methodInsertAsync
    public async ValueTask InsertAsync(OutboxMessage record, IOutboxTransactionContext transaction, CancellationToken cancellationToken = default)

    Inserts a single message into the outbox table atomically within the specified transaction.

    record: OutboxMessage
    The message to insert into the outbox.
    transaction: IOutboxTransactionContext
    The context representing the active database transaction.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • methodInsertBatchAsync
    public async ValueTask InsertBatchAsync(ReadOnlyMemory<OutboxMessage> records, IOutboxTransactionContext transaction, CancellationToken cancellationToken = default)

    Inserts a batch of messages into the outbox table in a single round-trip.

    records: ReadOnlyMemory<OutboxMessage>
    The batch of messages to insert.
    transaction: IOutboxTransactionContext
    The context representing the active database transaction.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Implementations should use bulk insert mechanisms (e.g., COPY, UNNEST, or table-valued parameters). If native bulk insert is unavailable, implementations fall back to individual inserts.

  • methodInsertBulkAsync
    public async Task InsertBulkAsync(IReadOnlyList<OutboxMessage> records, CancellationToken cancellationToken = default)

    Bulk-imports messages using PostgreSQL BINARY COPY for maximum throughput (non-transactional).

    records: IReadOnlyList<OutboxMessage>
    cancellationToken: CancellationToken
  • methodInsertBulkAsync
    public async Task InsertBulkAsync(IReadOnlyList<OutboxMessage> records, IOutboxTransactionContext transaction, CancellationToken cancellationToken = default)

    Inserts a batch of outbox messages using PostgreSQL binary COPY enlisted in the specified transaction.

    records: IReadOnlyList<OutboxMessage>
    transaction: IOutboxTransactionContext
    cancellationToken: CancellationToken
  • methodMarkAsDispatchedAsync
    public async ValueTask MarkAsDispatchedAsync(IReadOnlyList<OutboxMessage> messages, CancellationToken cancellationToken = default)

    Atomically marks the specified messages as successfully dispatched.

    messages: IReadOnlyList<OutboxMessage>
    The collection of messages to mark as dispatched.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • methodMarkAsFailedAsync
    public async ValueTask MarkAsFailedAsync(IReadOnlyList<OutboxMessage> messages, string error, bool isDeadLetter = false, CancellationToken cancellationToken = default)

    Marks the specified messages as failed, updating their error details and retry counts.

    messages: IReadOnlyList<OutboxMessage>
    The collection of messages that failed to process.
    error: string
    The error message or exception details causing the failure.
    isDeadLetter: bool
    `true` to mark the messages as permanently failed (dead letter); otherwise, `false`.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Is typically invoked by `Retry.RetryDispatcherInterceptor` when publishing fails. If the maximum retry attempts are exhausted, the message may be marked as a dead letter. Security Warning: The `error` parameter may contain sensitive information (such as connection strings in stack traces). Ensure exceptions are sanitized in production environments before they are persisted, to prevent leaking sensitive data.

  • methodPurgeDispatchedMessagesAsync
    public async ValueTask<int> PurgeDispatchedMessagesAsync(DateTimeOffset cutoff, int batchSize = 1000, CancellationToken cancellationToken = default)

    Purges dispatched messages that were processed prior to the specified cutoff timestamp. Used by `Hosting.OutboxCleanupService` when `DeleteOnDispatch = false`.

    cutoff: DateTimeOffset
    The cutoff timestamp; messages dispatched prior to this time will be deleted.
    batchSize: int
    The maximum number of rows to delete in a single batch.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation, returning the number of purged rows.

  • methodReclaimStaleMessagesAsync
    public async ValueTask<int> ReclaimStaleMessagesAsync(TimeSpan staleTimeout, CancellationToken cancellationToken = default)

    Reclaims messages that have remained in the InFlight state longer than the specified timeout.

    staleTimeout: TimeSpan
    The duration after which an InFlight message is considered abandoned.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the number of messages reclaimed.

    This mechanism prevents message loss if a dispatcher crashes after claiming a batch (transitioning from state 0 to 1) but before marking it as dispatched. Implementations must atomically reset these messages to the Pending state (0) if their last updated time is older than the current UTC time minus the stale timeout.

class

PostgreSqlOutboxRlsDdl

Ensamblado: EricksonLopez.Outbox.Storage.PostgreSql
public static partial class PostgreSqlOutboxRlsDdl

Generates hardened PostgreSQL 16+ `SECURITY DEFINER` stored functions with pinned `search_path` enabling least-privilege `NOBYPASSRLS` workers (such as `app_user`) to claim, complete, fail, and reclaim outbox messages safely when `FORCE ROW LEVEL SECURITY` is enabled on the outbox table.

Miembros (1)

  • methodBuildSecurityDefinerWorkerFunctionsSql
    public static string BuildSecurityDefinerWorkerFunctionsSql(string schema = "", string table = "", string lockOwnerColumn = "", string leaseExpirationColumn = "", string tenantColumn = "", string? workerRole = null)

    Builds idempotent PostgreSQL DDL defining `claim_pending_messages`, `complete_outbox_message`, `fail_outbox_message`, `reclaim_stale_messages`, and `get_pending_count` as `SECURITY DEFINER` functions with `SET search_path = pg_catalog, {schema}` and explicit `EXECUTE` grants to `workerRole`.

    schema: string
    table: string
    lockOwnerColumn: string
    leaseExpirationColumn: string
    tenantColumn: string
    workerRole: string?
class

PostgreSqlOutboxSetup

Ensamblado: EricksonLopez.Outbox.Storage.PostgreSql
public static class PostgreSqlOutboxSetup

Provides extension methods for configuring PostgreSQL outbox storage.

Miembros (7)

  • methodUsePostgreSql
    public static OutboxOptions UsePostgreSql(this OutboxOptions options, Func<IServiceProvider, NpgsqlDataSource> dataSourceFactory)

    Configures the outbox to use PostgreSQL as the storage engine using the provided data source factory.

    options: this OutboxOptions
    The outbox options being configured.
    dataSourceFactory: Func<IServiceProvider, NpgsqlDataSource>
    A factory delegate to provide an `NpgsqlDataSource` based on the `IServiceProvider`.

    Retorna: The original `OutboxOptions` for method chaining.

    Exceptions: ArgumentNullException: `options` or `dataSourceFactory` is `null`

  • methodUsePostgreSql
    public static OutboxOptions UsePostgreSql(this OutboxOptions options, Func<IServiceProvider, NpgsqlDataSource> dataSourceFactory, Action<PostgreSqlStorageOptions>? configureStorage)

    Configures the outbox to use PostgreSQL as the storage engine using the provided data source factory and storage options.

    options: this OutboxOptions
    The outbox options being configured.
    dataSourceFactory: Func<IServiceProvider, NpgsqlDataSource>
    A factory delegate to provide an `NpgsqlDataSource` based on the `IServiceProvider`.
    configureStorage: Action<PostgreSqlStorageOptions>?
    An optional action to configure PostgreSQL-specific storage options (SKIP LOCKED, session context, dead letter retries).

    Retorna: The original `OutboxOptions` for method chaining.

    Exceptions: ArgumentNullException: `options` or `dataSourceFactory` is `null`

  • methodUsePostgreSql
    public static OutboxOptions UsePostgreSql(this OutboxOptions options, string connectionString)

    Configures the outbox to use PostgreSQL as the storage engine using the provided connection string.

    options: this OutboxOptions
    The outbox options being configured.
    connectionString: string
    The PostgreSQL connection string used to connect to the database.

    Retorna: The original `OutboxOptions` for method chaining.

    Exceptions: ArgumentNullException: `options` is `null`; ArgumentException: `connectionString` is `null` or whitespace

  • methodUsePostgreSql
    public static OutboxOptions UsePostgreSql(this OutboxOptions options, string connectionString, Action<PostgreSqlStorageOptions>? configureStorage)

    Configures the outbox to use PostgreSQL as the storage engine using the provided connection string and storage options.

    options: this OutboxOptions
    The outbox options being configured.
    connectionString: string
    The PostgreSQL connection string used to connect to the database.
    configureStorage: Action<PostgreSqlStorageOptions>?
    An optional action to configure PostgreSQL-specific storage options.

    Retorna: The original `OutboxOptions` for method chaining.

    Exceptions: ArgumentNullException: `options` is `null`; ArgumentException: `connectionString` is `null` or whitespace

  • methodUsePostgreSqlNotifications
    public static OutboxOptions UsePostgreSqlNotifications(this OutboxOptions options)

    Registers the `PostgresNotificationListener` background service to enable sub-millisecond wakeup latency via PostgreSQL `LISTEN`/`NOTIFY`.

    options: this OutboxOptions
    The outbox options being configured.

    Retorna: The original `OutboxOptions` for method chaining.

    When registered, a dedicated background connection subscribes to the `outbox_new_messages` channel. Each INSERT into the outbox table fires a trigger that sends a `NOTIFY`, waking the dispatcher immediately instead of waiting for the next polling interval. Prerequisites: The SQL trigger defined in `Outbox_DDL.sql` must be installed on the database. Execute after `UsePostgreSql(OutboxOptions, string)`. Optional: Not called automatically by `UsePostgreSql(OutboxOptions, string)`. If you do not need low-latency dispatch (e.g., your polling interval is already < 1 second), you may omit this call to save one dedicated idle DB connection. Exceptions: ArgumentNullException: `options` is `null` Example:

    services.AddOutbox(options =>
    {
        options
            .UsePostgreSql(connectionString)
            .UsePostgreSqlNotifications()  // optional — enables LISTEN/NOTIFY wakeup
            .UseGeneratedTypes(MyJsonContext.Default);
    });
  • methodUsePostgreSqlSessionContext
    public static OutboxOptions UsePostgreSqlSessionContext(this OutboxOptions options, Action<PostgreSqlStorageOptions>? configureStorage = null)

    Registers the `PostgreSqlSessionContextMiddleware` in the dispatch pipeline to propagate tenant context (`set_config('app.current_company_id', ...)`) to PostgreSQL sessions.

    options: this OutboxOptions
    The outbox options being configured.
    configureStorage: Action<PostgreSqlStorageOptions>?
    An optional action to configure session context options.

    Retorna: The original `OutboxOptions` for method chaining.

    Exceptions: ArgumentNullException: `options` is `null`

  • methodUseRlsAwarePostgreSql
    public static OutboxOptions UseRlsAwarePostgreSql(this OutboxOptions options, string connectionString, Action<PostgreSqlStorageOptions>? configureStorage = null)

    Configures the outbox to use `RlsAwarePostgreSqlOutboxStorage` with dual `tenant_id` + `company_id` Row-Level Security (RLS) awareness and chunked batch persistence.

    options: this OutboxOptions
    The outbox options being configured.
    connectionString: string
    The PostgreSQL connection string.
    configureStorage: Action<PostgreSqlStorageOptions>?
    Optional storage options customization.

    Retorna: The original `OutboxOptions` for chaining.

class

PostgreSqlSessionContext

Ensamblado: EricksonLopez.Outbox.Storage.PostgreSql
public sealed partial class PostgreSqlSessionContext : IPostgreSqlSessionContext
Implementa: IPostgreSqlSessionContext

Provides PostgreSQL session context configuration (such as tenant/company context propagation) for Row Level Security (RLS) and multi-tenant database isolation.

Miembros (8)

  • constructorPostgreSqlSessionContext
    public PostgreSqlSessionContext(IOptions<PostgreSqlStorageOptions>? options = null)

    Initializes a new instance of the `PostgreSqlSessionContext` class for connection-scoped usage.

    options: IOptions<PostgreSqlStorageOptions>?
    The PostgreSQL storage options.
  • constructorPostgreSqlSessionContext
    public PostgreSqlSessionContext(NpgsqlDataSource dataSource, IOptions<PostgreSqlStorageOptions>? options = null)

    Initializes a new instance of the `PostgreSqlSessionContext` class.

    dataSource: NpgsqlDataSource
    The PostgreSQL data source.
    options: IOptions<PostgreSqlStorageOptions>?
    The PostgreSQL storage options.

    Exceptions: ArgumentNullException: `dataSource` is `null`

  • methodApplyDispatchContextAsync
    public async ValueTask ApplyDispatchContextAsync(NpgsqlConnection connection, NpgsqlTransaction transaction, OutboxDispatchTenantContext context, CancellationToken cancellationToken = default)

    Applies the rehydrated multi-plane `OutboxDispatchTenantContext` (`app.current_plane`, `app.current_tenant_id`, `app.current_company_id`) onto an active `NpgsqlTransaction` in a single roundtrip using transaction-scoped `set_config(..., true)`.

    connection: NpgsqlConnection
    transaction: NpgsqlTransaction
    context: OutboxDispatchTenantContext
    cancellationToken: CancellationToken
  • methodApplyTenantSessionContextAsync
    public ValueTask ApplyTenantSessionContextAsync(IDbConnection connection, string? tenantId, bool? isLocal = null, IDbTransaction? transaction = null, CancellationToken cancellationToken = default)

    Applies or resets the primary and any additional configured tenant session context parameters on the specified PostgreSQL connection and optional transaction. When `tenantId` is `null` or whitespace, the session context parameters are reset to empty strings.

    connection: IDbConnection
    The PostgreSQL connection.
    tenantId: string?
    The tenant or company identifier value, or `null` to clear.
    isLocal: bool?
    Whether the setting is local to the current transaction. If null, uses the configured default.
    transaction: IDbTransaction?
    The optional PostgreSQL transaction.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation.

  • methodApplyTenantSessionContextAsync
    public ValueTask ApplyTenantSessionContextAsync(NpgsqlConnection connection, string? tenantId, bool? isLocal = null, NpgsqlTransaction? transaction = null, CancellationToken cancellationToken = default)

    Applies or resets the primary and any additional configured tenant session context parameters on the specified PostgreSQL connection and optional transaction. When `tenantId` is `null` or whitespace, the session context parameters are reset to empty strings.

    connection: NpgsqlConnection
    The PostgreSQL connection.
    tenantId: string?
    The tenant or company identifier value, or `null` to clear.
    isLocal: bool?
    Whether the setting is local to the current transaction. If null, uses the configured default.
    transaction: NpgsqlTransaction?
    The optional PostgreSQL transaction.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation.

  • methodResetSessionContextAsync
    public async ValueTask ResetSessionContextAsync(NpgsqlConnection connection, bool? isLocal = null, NpgsqlTransaction? transaction = null, CancellationToken cancellationToken = default)

    Resets the session context parameter on the specified PostgreSQL connection to an empty value.

    connection: NpgsqlConnection
    The PostgreSQL connection.
    isLocal: bool?
    Whether the setting reset is local to the current transaction. If null, uses the configured default.
    transaction: NpgsqlTransaction?
    The optional PostgreSQL transaction.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation.

  • methodSetSessionContextAsync
    public async ValueTask SetSessionContextAsync(NpgsqlConnection connection, string tenantId, bool? isLocal = null, NpgsqlTransaction? transaction = null, CancellationToken cancellationToken = default)

    Sets the session context parameter on the specified PostgreSQL connection.

    connection: NpgsqlConnection
    The PostgreSQL connection.
    tenantId: string
    The tenant or company identifier value.
    isLocal: bool?
    Whether the setting is local to the current transaction. If null, uses the configured default.
    transaction: NpgsqlTransaction?
    The optional PostgreSQL transaction.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation.

  • methodSetSessionContextAsync
    public async ValueTask SetSessionContextAsync(string tenantId, bool? isLocal = null, CancellationToken cancellationToken = default)

    Opens a connection from the configured data source and sets the session context parameter.

    tenantId: string
    The tenant or company identifier value.
    isLocal: bool?
    Whether the setting is local to the current transaction. If null, uses the configured default.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation.

class

PostgreSqlSessionContextMiddleware

Ensamblado: EricksonLopez.Outbox.Storage.PostgreSql
public sealed class PostgreSqlSessionContextMiddleware : IOutboxMiddleware
Implementa: IOutboxMiddleware

Pipeline middleware that rehydrates `OutboxDispatchTenantContext` (`TenantId`, `CompanyId`, `ExecutionPlane`) per message into `IOutboxDispatchContextAccessor` and optional `PostgreSqlStorageOptions.PerMessageDispatchScopeCallback` prior to background message dispatch.

Miembros (3)

  • constructorPostgreSqlSessionContextMiddleware
    public PostgreSqlSessionContextMiddleware(IPostgreSqlSessionContext sessionContext, IOptions<PostgreSqlStorageOptions> options, ILogger<PostgreSqlSessionContextMiddleware> logger, IOutboxDispatchContextAccessor? dispatchContextAccessor = null)

    Initializes a new instance of the `PostgreSqlSessionContextMiddleware` class.

    sessionContext: IPostgreSqlSessionContext
    options: IOptions<PostgreSqlStorageOptions>
    logger: ILogger<PostgreSqlSessionContextMiddleware>
    dispatchContextAccessor: IOutboxDispatchContextAccessor?
  • methodInvokeAsync
    public async ValueTask<DispatchResult> InvokeAsync(OutboxMessage message, OutboxMessageMetadata metadata, OutboxPipelineDelegate next, CancellationToken cancellationToken)

    Invokes the middleware logic for the given message.

    message: OutboxMessage
    The outbox message being processed.
    metadata: OutboxMessageMetadata
    The metadata associated with the outbox message.
    next: OutboxPipelineDelegate
    The next delegate in the pipeline chain.
    cancellationToken: CancellationToken
    A token that can be used to cancel the middleware execution.

    Retorna: A task representing the asynchronous operation, containing the `DispatchResult`.

  • methodResolveDispatchContext
    public static OutboxDispatchTenantContext ResolveDispatchContext(OutboxMessage message, OutboxMessageMetadata metadata)

    Extracts the normalized `OutboxDispatchTenantContext` (`TenantId`, `CompanyId`, `ExecutionPlane`) from an outbox message and its metadata headers.

    message: OutboxMessage
    metadata: OutboxMessageMetadata
class

PostgreSqlStorageOptions

Ensamblado: EricksonLopez.Outbox.Storage.PostgreSql
public sealed class PostgreSqlStorageOptions

Configuration options specific to the PostgreSQL outbox storage engine, including multi-tenant Row-Level Security (RLS), configurable lease owner columns (`locked_by` / `owner_id`), `SECURITY DEFINER` worker functions, and per-message context rehydration.

Miembros (34)

  • methodConfigureRlsLockedBySchema
    public PostgreSqlStorageOptions ConfigureRlsLockedBySchema(string? claimPendingFunction = null, string? completeMessageFunction = null, string? failMessageFunction = null, string? tenantInsertFallbackSqlFunction = "")

    Configures the storage options for a `FORCE ROW LEVEL SECURITY` multi-tenant PostgreSQL schema using `locked_by VARCHAR`, `locked_until TIMESTAMPTZ`, and `company_id UUID`.

    claimPendingFunction: string?
    Optional `SECURITY DEFINER` claim function (e.g., `outbox.claim_pending_messages`).
    completeMessageFunction: string?
    Optional `SECURITY DEFINER` per-message completion function (e.g., `outbox.complete_outbox_message`).
    failMessageFunction: string?
    Optional `SECURITY DEFINER` per-message failure function (e.g., `outbox.fail_outbox_message`).
    tenantInsertFallbackSqlFunction: string?
    Optional SQL function fallback for `company_id` on insert (e.g., `core.current_company_id()`).

    Retorna: This `PostgreSqlStorageOptions` instance for chaining.

  • propertyAdditionalSessionContextSettingNames
    public IReadOnlyList<string> AdditionalSessionContextSettingNames { get; set; }

    Gets or sets additional PostgreSQL session setting names to populate alongside `SessionContextSettingName` during multi-tenant RLS context propagation (e.g., `app.current_tenant_id`, `app.current_tenant`).

  • propertyClaimPendingFunctionName
    public string? ClaimPendingFunctionName { get; set; }

    Gets or sets an optional schema-qualified `SECURITY DEFINER` PostgreSQL function name (e.g., `outbox.claim_pending_messages`) invoked with `(@OwnerId, @BatchSize, @LeaseSeconds)` so background workers running as `NOBYPASSRLS` roles (`app_user`) can atomically claim pending messages across tenants under `FORCE ROW LEVEL SECURITY`.

  • propertyCompanyColumnIsUuid
    public bool CompanyColumnIsUuid { get; set; }

    Gets or sets whether `CompanyColumnName` is typed as PostgreSQL `UUID`. Default is `true`.

  • propertyCompanyColumnName
    public string CompanyColumnName { get; set; }

    Gets or sets the holding company column name when `EnableCompanyColumn` is enabled. Default is `company_id`.

  • propertyCompanyInsertFallbackSqlFunction
    public string? CompanyInsertFallbackSqlFunction { get; set; }

    Gets or sets an optional SQL fallback function expression (such as `core.current_company_id()`) for `CompanyColumnName` on insert.

  • propertyCompleteMessageFunctionName
    public string? CompleteMessageFunctionName { get; set; }

    Gets or sets an optional schema-qualified `SECURITY DEFINER` PostgreSQL function name (e.g., `outbox.complete_outbox_message`) invoked per completed message inside a single pipelined `NpgsqlBatch` with `(@Id, @OwnerId)`.

  • propertyCompleteMessagesBatchFunctionName
    public string? CompleteMessagesBatchFunctionName { get; set; }

    Gets or sets an optional schema-qualified `SECURITY DEFINER` PostgreSQL batch function name (e.g., `outbox.complete_messages`) invoked once per batch with `(@OwnerId, @Ids, @CreatedAts, @DeleteOnDispatch)`.

  • propertyCustomClaimPendingCallback
    public Func<NpgsqlConnection, string, int, TimeSpan, CancellationToken, ValueTask<IReadOnlyList<OutboxMessage>>>? CustomClaimPendingCallback { get; set; }

    Gets or sets an optional custom override delegate for claiming pending messages when bespoke stored-function parameter signatures are required.

  • propertyCustomMarkDispatchedCallback
    public Func<NpgsqlConnection, string, IReadOnlyList<OutboxMessage>, CancellationToken, ValueTask>? CustomMarkDispatchedCallback { get; set; }

    Gets or sets an optional custom override delegate for marking claimed messages as dispatched.

  • propertyCustomMarkFailedCallback
    public Func<NpgsqlConnection, string, IReadOnlyList<OutboxMessage>, string, bool, CancellationToken, ValueTask>? CustomMarkFailedCallback { get; set; }

    Gets or sets an optional custom override delegate for marking claimed messages as failed or dead-lettered.

  • propertyEnableAtomicDeadLetterTransfer
    public bool EnableAtomicDeadLetterTransfer { get; set; }

    Gets or sets whether messages exceeding max retries are atomically moved to the dead-letter table. Default is `true`.

  • propertyEnableCompanyColumn
    public bool EnableCompanyColumn { get; set; }

    Gets or sets whether the outbox table includes an explicit secondary holding `company_id` column alongside `tenant_id`.

  • propertyEnableSessionContextPropagation
    public bool EnableSessionContextPropagation { get; set; }

    Gets or sets whether to automatically propagate the message's tenant and company context during background dispatch. Default is `true`.

  • propertyEnableTenantColumn
    public bool EnableTenantColumn { get; set; }

    Gets or sets whether the outbox table includes a dedicated tenant/company column for PostgreSQL Row-Level Security (RLS). Default is `false` for backward compatibility with single-tenant schemas.

  • propertyFailMessageFunctionName
    public string? FailMessageFunctionName { get; set; }

    Gets or sets an optional schema-qualified `SECURITY DEFINER` PostgreSQL function name (e.g., `outbox.fail_outbox_message`) invoked per failed message inside a single pipelined `NpgsqlBatch` with `(@Id, @OwnerId, @Error, @IsDeadLetter, @MaxBackoffSeconds)`.

  • propertyFailMessagesBatchFunctionName
    public string? FailMessagesBatchFunctionName { get; set; }

    Gets or sets an optional schema-qualified `SECURITY DEFINER` PostgreSQL batch function name (e.g., `outbox.fail_messages`) invoked once per batch with `(@OwnerId, @Ids, @CreatedAts, @State, @Error, @MaxBackoffSeconds)`.

  • propertyGetPendingCountFunctionName
    public string? GetPendingCountFunctionName { get; set; }

    Gets or sets an optional schema-qualified `SECURITY DEFINER` PostgreSQL function name (e.g., `outbox.get_pending_count`) invoked with no arguments (or `()`) to count pending messages under `FORCE ROW LEVEL SECURITY`.

  • propertyLeaseDuration
    public TimeSpan LeaseDuration { get; set; }

    Gets or sets the lease duration applied when claiming pending messages via `LeaseExpirationColumnName` or `ClaimPendingFunctionName`. Default is 60 seconds.

  • propertyLeaseExpirationColumnName
    public string? LeaseExpirationColumnName { get; set; }

    Gets or sets an optional lease-expiration timestamp column name (such as `locked_until`) updated when claiming pending messages and cleared upon completion, failure, or stale lease reclamation.

  • propertyLockOwnerColumnIsText
    public bool LockOwnerColumnIsText { get; set; }

    Gets or sets whether `LockOwnerColumnName` is typed as `VARCHAR`/`TEXT` rather than `UUID`. Default is `false` (`UUID`); set `true` when `locked_by` is `VARCHAR(64)`.

  • propertyLockOwnerColumnName
    public string LockOwnerColumnName { get; set; }

    Gets or sets the column name used to record the worker instance holding the active dispatch lease (e.g., `owner_id` or `locked_by`). Default is `owner_id` for backward compatibility with canonical `Outbox_DDL.sql`; set to `locked_by` for lease-based RLS schemas.

  • propertyMaxDeliveryRetries
    public int MaxDeliveryRetries { get; set; }

    Gets or sets the maximum number of delivery retry attempts before a message is moved to the dead-letter queue. Default is 5 (aligned with enterprise production standard).

  • propertyMaxInsertBatchChunkSize
    public int MaxInsertBatchChunkSize { get; set; }

    Gets or sets the maximum number of messages written per PostgreSQL batch statement before automatic chunking. Default is 1,000 rows to stay well under PostgreSQL's 65,535 wire parameter ceiling.

  • propertyPerMessageDispatchScopeCallback
    public Func<OutboxMessage, OutboxMessageMetadata, OutboxDispatchTenantContext, CancellationToken, ValueTask<IDisposable?>>? PerMessageDispatchScopeCallback { get; set; }

    Gets or sets an optional per-message ambient scope factory invoked by `PostgreSqlSessionContextMiddleware` to rehydrate application execution context (`TenantId`, `CompanyId`, `ExecutionPlane`) before dispatching each message.

  • propertyPlaneSessionSettingName
    public string PlaneSessionSettingName { get; set; }

    Gets or sets the PostgreSQL session setting name used for the multi-plane execution discriminator (`TENANT` vs `CONTROL`). Default is `app.current_plane`.

  • propertyReclaimStaleFunctionName
    public string? ReclaimStaleFunctionName { get; set; }

    Gets or sets an optional schema-qualified `SECURITY DEFINER` PostgreSQL function name (e.g., `outbox.reclaim_stale_messages`) invoked with `(@StaleSeconds, @MaxAgeDays, @ReclaimLimit, @MaxRetryCount)` to recover expired leases under `FORCE ROW LEVEL SECURITY`.

  • propertySessionContextIsLocal
    public bool SessionContextIsLocal { get; set; }

    Gets or sets whether the session context setting is local to the current transaction. When `true`, executes `set_config(name, value, true)`. Default is `true`.

  • propertySessionContextSettingName
    public string SessionContextSettingName { get; set; }

    Gets or sets the name of the PostgreSQL session setting used for tenant/company isolation (RLS). Default is `app.current_company_id`.

  • propertyTenantColumnIsUuid
    public bool TenantColumnIsUuid { get; set; }

    Gets or sets whether `TenantColumnName` is typed as PostgreSQL `UUID` rather than `VARCHAR`/`TEXT`. Default is `false` for backward compatibility; set `true` when `company_id` is `UUID`.

  • propertyTenantColumnName
    public string TenantColumnName { get; set; }

    Gets or sets the column name in the outbox table used to store the tenant/company identifier when `EnableTenantColumn` is enabled. Default is `company_id`.

  • propertyTenantInsertFallbackSqlFunction
    public string? TenantInsertFallbackSqlFunction { get; set; }

    Gets or sets an optional SQL function call expression (such as `core.current_company_id()`) used via `COALESCE(@TenantId, expr)` during transactional `INSERT` / `UNNEST` when `EnableTenantColumn` and `TenantColumnIsUuid` are enabled.

  • propertyUseSkipLocked
    public bool UseSkipLocked { get; set; }

    Gets or sets whether to use `FOR UPDATE SKIP LOCKED` during polling to prevent lock contention across multiple consumers. Default is `true`.

  • propertyWorkerSessionContextCallback
    public Func<NpgsqlConnection, NpgsqlTransaction, CancellationToken, ValueTask>? WorkerSessionContextCallback { get; set; }

    Gets or sets an optional transaction-scoped session initialization callback executed inside an explicit `NpgsqlTransaction` before background worker repository operations when direct table SQL is used under Row-Level Security.

class

PostgresNotificationListener

Ensamblado: EricksonLopez.Outbox.Storage.PostgreSql
public sealed class PostgresNotificationListener : BackgroundService
Hereda de: BackgroundService

Provides a dedicated background listener for PostgreSQL `LISTEN`/`NOTIFY` commands.

Notas:

Provides sub-millisecond wakeup latency for the Outbox Dispatcher by actively listening to PostgreSQL notifications rather than relying solely on polling. Includes an infinite retry loop to handle database disconnects gracefully.

Miembros (3)

  • constructorPostgresNotificationListener
    public PostgresNotificationListener(NpgsqlDataSource dataSource, ILogger<PostgresNotificationListener> logger, TimeProvider timeProvider, IPollerWakeup? pollerWakeup = null)

    Initializes a new instance of the `PostgresNotificationListener` class.

    dataSource: NpgsqlDataSource
    The PostgreSQL data source that creates connections.
    logger: ILogger<PostgresNotificationListener>
    The logger that records listener activity and errors.
    timeProvider: TimeProvider
    The time provider for deterministic testing.
    pollerWakeup: IPollerWakeup?
    The wakeup signal interface to trigger the dispatcher poller (optional).
  • eventOnListeningStarted
    public event EventHandler? OnListeningStarted

    Event raised when the listener has successfully connected and subscribed to the notification channel.

  • eventOnMessageReceived
    public event EventHandler? OnMessageReceived

    Event raised when a notification message is received from PostgreSQL.

class

RlsAwarePostgreSqlOutboxStorage

Ensamblado: EricksonLopez.Outbox.Storage.PostgreSql
public sealed partial class RlsAwarePostgreSqlOutboxStorage : IOutboxRepository
Implementa: IOutboxRepository

Multi-plane Row-Level Security (RLS)-aware PostgreSQL `IOutboxRepository` supporting dual `tenant_id` and `company_id` isolation columns, transaction-scoped `set_config(..., true)` worker GUC initialization, and automatic 1,000-row batch chunking.

Miembros (12)

  • constructorRlsAwarePostgreSqlOutboxStorage
    public RlsAwarePostgreSqlOutboxStorage(NpgsqlDataSource dataSource, IOptions<OutboxRuntimeOptions>? runtimeOptions = null, IOptions<PostgreSqlStorageOptions>? storageOptions = null)

    Initializes a new instance of the `RlsAwarePostgreSqlOutboxStorage` class.

    dataSource: NpgsqlDataSource
    The PostgreSQL data source.
    runtimeOptions: IOptions<OutboxRuntimeOptions>?
    Optional outbox runtime options.
    storageOptions: IOptions<PostgreSqlStorageOptions>?
    Optional PostgreSQL RLS storage options.
  • methodBuildRlsTableAndPolicyDdl
    public static string BuildRlsTableAndPolicyDdl(string schema = "", string table = "", string tenantColumn = "", string companyColumn = "")

    Generates idempotent PostgreSQL DDL enabling `ENABLE ROW LEVEL SECURITY` and `FORCE ROW LEVEL SECURITY` on an outbox table partitioned by `tenantColumn` and `companyColumn`.

    schema: string
    table: string
    tenantColumn: string
    companyColumn: string
  • methodFetchPendingAsync
    public ValueTask<IReadOnlyList<OutboxMessage>> FetchPendingAsync(int batchSize, CancellationToken cancellationToken = default)

    Retrieves a batch of pending messages ready for delivery.

    batchSize: int
    The maximum number of messages to retrieve.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the batch of messages retrieved.

    The method fetches up to the specified batch size of messages that are in the Pending state (0) and whose delivery time is less than or equal to the current UTC time. Implementations guarantee safe concurrent polling by using SKIP LOCKED or equivalent semantics, atomically transitioning the fetched messages to the InFlight state (1). Scheduling edge case — `deliver_at` vs `MaxMessageAge`: Messages stored with a future `deliver_at` timestamp that exceeds `MaxMessageAge` will be silently excluded from polling by the `created_at` age guard. Such messages will not be processed and will not be automatically dead-lettered. Ensure `OutboxRuntimeOptions.MaxMessageAge` is greater than the maximum `deliver_at` offset used in your application (e.g., if scheduling up to 7 days ahead, set `MaxMessageAge ≥ 8 days`). Ordering with multiple dispatcher instances: When multiple dispatcher instances run concurrently, messages are fetched in `ORDER BY created_at ASC, id ASC` order but can be claimed by different instances via `SKIP LOCKED`, resulting in non-deterministic global ordering. In partitioned table setups, the order guarantee applies within each partition only. For strict global ordering, use a single dispatcher instance with `MaxDegreeOfParallelism = 1`.

  • methodGetPendingCountAsync
    public ValueTask<long> GetPendingCountAsync(CancellationToken cancellationToken = default)

    Retrieves the approximate count of messages awaiting processing.

    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the approximate pending message count.

    Includes messages in the Pending (0) or Failed (3) states for metrics and monitoring.

  • methodInsertAsync
    public async ValueTask InsertAsync(OutboxMessage record, IOutboxTransactionContext transaction, CancellationToken cancellationToken = default)

    Inserts a single message into the outbox table atomically within the specified transaction.

    record: OutboxMessage
    The message to insert into the outbox.
    transaction: IOutboxTransactionContext
    The context representing the active database transaction.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • methodInsertBatchAsync
    public async ValueTask InsertBatchAsync(ReadOnlyMemory<OutboxMessage> records, IOutboxTransactionContext transaction, CancellationToken cancellationToken = default)

    Inserts a batch of messages into the outbox table in a single round-trip.

    records: ReadOnlyMemory<OutboxMessage>
    The batch of messages to insert.
    transaction: IOutboxTransactionContext
    The context representing the active database transaction.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Implementations should use bulk insert mechanisms (e.g., COPY, UNNEST, or table-valued parameters). If native bulk insert is unavailable, implementations fall back to individual inserts.

  • methodMarkAsDispatchedAsync
    public ValueTask MarkAsDispatchedAsync(IReadOnlyList<OutboxMessage> messages, CancellationToken cancellationToken = default)

    Atomically marks the specified messages as successfully dispatched.

    messages: IReadOnlyList<OutboxMessage>
    The collection of messages to mark as dispatched.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • methodMarkAsFailedAsync
    public ValueTask MarkAsFailedAsync(IReadOnlyList<OutboxMessage> messages, string error, bool isDeadLetter = false, CancellationToken cancellationToken = default)

    Marks the specified messages as failed, updating their error details and retry counts.

    messages: IReadOnlyList<OutboxMessage>
    The collection of messages that failed to process.
    error: string
    The error message or exception details causing the failure.
    isDeadLetter: bool
    `true` to mark the messages as permanently failed (dead letter); otherwise, `false`.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Is typically invoked by `Retry.RetryDispatcherInterceptor` when publishing fails. If the maximum retry attempts are exhausted, the message may be marked as a dead letter. Security Warning: The `error` parameter may contain sensitive information (such as connection strings in stack traces). Ensure exceptions are sanitized in production environments before they are persisted, to prevent leaking sensitive data.

  • methodReclaimStaleMessagesAsync
    public ValueTask<int> ReclaimStaleMessagesAsync(TimeSpan staleTimeout, CancellationToken cancellationToken = default)

    Reclaims messages that have remained in the InFlight state longer than the specified timeout.

    staleTimeout: TimeSpan
    The duration after which an InFlight message is considered abandoned.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the number of messages reclaimed.

    This mechanism prevents message loss if a dispatcher crashes after claiming a batch (transitioning from state 0 to 1) but before marking it as dispatched. Implementations must atomically reset these messages to the Pending state (0) if their last updated time is older than the current UTC time minus the stale timeout.

  • propertyDualScopeInsertSql
    public string DualScopeInsertSql { get; }

    Gets the parameterized single-row SQL statement generated for dual `tenant_id` + `company_id` inserts.

  • propertyMaxBatchChunkSize
    public int MaxBatchChunkSize { get; }

    Gets the maximum number of rows written per chunked batch operation.

  • propertyWorkerPlaneInitSql
    public string WorkerPlaneInitSql { get; }

    Gets the transaction-local (`is_local = true`) worker session GUC initialization SQL.

EricksonLopez.Outbox.Storage.SqlServer#

4
class

SqlServerDeadLetterRepository

Ensamblado: EricksonLopez.Outbox.Storage.SqlServer
public sealed class SqlServerDeadLetterRepository : IDeadLetterRepository
Implementa: IDeadLetterRepository

Provides a SQL Server implementation of `IDeadLetterRepository`.

Miembros (6)

  • constructorSqlServerDeadLetterRepository
    public SqlServerDeadLetterRepository(Func<IDbConnection> connectionFactory, IOptionsMonitor<OutboxRuntimeOptions> options)

    Initializes a new instance of the `SqlServerDeadLetterRepository` class.

    connectionFactory: Func<IDbConnection>
    The factory that creates SQL Server connections.
    options: IOptionsMonitor<OutboxRuntimeOptions>
    The outbox runtime options.

    Exceptions: ArgumentNullException: `connectionFactory` or `options` is `null`; ArgumentException: The configured schema or table name in `options` contains invalid characters.

  • methodDeleteAsync
    public async ValueTask DeleteAsync(Guid id, CancellationToken cancellationToken = default)

    Deletes a dead-lettered message by its unique identifier.

    id: Guid
    The unique identifier of the dead-lettered message to delete.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • methodGetAsync
    public async ValueTask<IReadOnlyList<DeadLetterMessage>> GetAsync(int limit = 100, DateTimeOffset? after = null, CancellationToken cancellationToken = default)

    Retrieves a page of dead-lettered messages for inspection or replay.

    limit: int
    The maximum number of records to return.
    after: DateTimeOffset?
    The cursor indicating to return records dead-lettered after this timestamp. Pass `DateTimeOffset.MinValue` for the first page.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the retrieved page of dead-lettered messages.

  • methodInsertAsync
    public async ValueTask InsertAsync(DeadLetterMessage message, IOutboxTransactionContext? transaction = default, CancellationToken cancellationToken = default)

    Persists a dead-lettered message.

    message: DeadLetterMessage
    The dead-lettered message to persist.
    transaction: IOutboxTransactionContext?
    The optional transaction context. If `null`, the repository must open its own connection and auto-commit the insert.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Called by the Dispatcher after a message has exhausted its `Retry.RetryPolicy`.

  • methodPurgeAsync
    public async ValueTask PurgeAsync(DateTimeOffset olderThan, CancellationToken cancellationToken = default)

    Purges all dead-lettered messages older than the specified timestamp.

    olderThan: DateTimeOffset
    The timestamp threshold; messages older than this value will be purged.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • propertyIsFirstPartyImplementation
    public bool IsFirstPartyImplementation { get; }

    Gets a value indicating whether this is a first-party (built-in) implementation.

    Used by `OutboxStartupValidator` to warn operators when a third-party `IDeadLetterRepository` is registered, reminding them to verify that their implementation correctly handles `transaction = null` (auto-commit mode). All first-party storage engine implementations override this to return `true`. Third-party implementations that do not override this will return `false`, triggering the startup advisory log message. This is a Zero-Reflection pattern: no `GetType().Name`, no string comparisons, no assembly scanning. The check is a simple virtual dispatch.

class

SqlServerIdempotencyRepository

Ensamblado: EricksonLopez.Outbox.Storage.SqlServer
public sealed class SqlServerIdempotencyRepository : IIdempotencyRepository
Implementa: IIdempotencyRepository

Provides a SQL Server implementation of `IIdempotencyRepository`.

Miembros (3)

  • constructorSqlServerIdempotencyRepository
    public SqlServerIdempotencyRepository(Func<IDbConnection> connectionFactory, IOptionsMonitor<OutboxRuntimeOptions> options)

    Initializes a new instance of the `SqlServerIdempotencyRepository` class.

    connectionFactory: Func<IDbConnection>
    The factory that creates SQL Server connections.
    options: IOptionsMonitor<OutboxRuntimeOptions>
    The outbox runtime options.

    Exceptions: ArgumentNullException: `connectionFactory` or `options` is `null`

  • methodPurgeExpiredRecordsAsync
    public async ValueTask PurgeExpiredRecordsAsync(DateTimeOffset olderThan, CancellationToken cancellationToken = default)

    Purges idempotency records older than the specified timestamp.

    olderThan: DateTimeOffset
    The timestamp threshold; records older than this value will be purged.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Called periodically by `InboxCleanupService` to prevent table bloat.

  • methodTryInsertAsync
    public async ValueTask<bool> TryInsertAsync(IdempotencyRecord record, EricksonLopez.Outbox.Persistence.IOutboxTransactionContext? transaction = default, CancellationToken cancellationToken = default)

    Attempts to insert an idempotency record.

    record: IdempotencyRecord
    The idempotency record to insert.
    transaction: EricksonLopez.Outbox.Persistence.IOutboxTransactionContext?
    The optional transaction context.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result is `true` if the record was inserted; otherwise, `false` if the record already exists (duplicate).

class

SqlServerOutboxRepository

Ensamblado: EricksonLopez.Outbox.Storage.SqlServer
public sealed class SqlServerOutboxRepository : IOutboxRepository
Implementa: IOutboxRepository

Provides a SQL Server implementation of `IOutboxRepository`. Uses `WITH (UPDLOCK, READPAST)` for concurrent polling.

Notas:

Concurrency semantics: - `READPAST` + `UPDLOCK` is the SQL Server equivalent of PostgreSQL's `FOR UPDATE SKIP LOCKED` when the isolation level is `READ COMMITTED` or `REPEATABLE READ`. - Under `SERIALIZABLE` isolation, READPAST silently fails (no rows are skipped). - SQL Server 2022+ natively supports `SKIP LOCKED`; consider migrating for strict equivalence. - Unlike PostgreSQL SKIP LOCKED, READPAST can skip non-locked rows on a locked PAGE in certain page-level locking scenarios. Production use requires READ COMMITTED isolation.

Miembros (9)

  • constructorSqlServerOutboxRepository
    public SqlServerOutboxRepository(Func<IDbConnection> connectionFactory, IOptions<OutboxRuntimeOptions>? options = null)

    Initializes a new instance of the `SqlServerOutboxRepository` class.

    connectionFactory: Func<IDbConnection>
    The factory that creates SQL Server connections.
    options: IOptions<OutboxRuntimeOptions>?
    The runtime options containing thresholds and configurations.

    Exceptions: ArgumentNullException: `connectionFactory` is `null`

  • methodFetchPendingAsync
    public async ValueTask<IReadOnlyList<OutboxMessage>> FetchPendingAsync(int batchSize, CancellationToken cancellationToken = default)

    Retrieves a batch of pending messages ready for delivery.

    batchSize: int
    The maximum number of messages to retrieve.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the batch of messages retrieved.

    The method fetches up to the specified batch size of messages that are in the Pending state (0) and whose delivery time is less than or equal to the current UTC time. Implementations guarantee safe concurrent polling by using SKIP LOCKED or equivalent semantics, atomically transitioning the fetched messages to the InFlight state (1). Scheduling edge case — `deliver_at` vs `MaxMessageAge`: Messages stored with a future `deliver_at` timestamp that exceeds `MaxMessageAge` will be silently excluded from polling by the `created_at` age guard. Such messages will not be processed and will not be automatically dead-lettered. Ensure `OutboxRuntimeOptions.MaxMessageAge` is greater than the maximum `deliver_at` offset used in your application (e.g., if scheduling up to 7 days ahead, set `MaxMessageAge ≥ 8 days`). Ordering with multiple dispatcher instances: When multiple dispatcher instances run concurrently, messages are fetched in `ORDER BY created_at ASC, id ASC` order but can be claimed by different instances via `SKIP LOCKED`, resulting in non-deterministic global ordering. In partitioned table setups, the order guarantee applies within each partition only. For strict global ordering, use a single dispatcher instance with `MaxDegreeOfParallelism = 1`.

  • methodGetPendingCountAsync
    public async ValueTask<long> GetPendingCountAsync(CancellationToken cancellationToken = default)

    Retrieves the approximate count of messages awaiting processing.

    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the approximate pending message count.

    Includes messages in the Pending (0) or Failed (3) states for metrics and monitoring.

  • methodInsertAsync
    public async ValueTask InsertAsync(OutboxMessage record, EricksonLopez.Outbox.Persistence.IOutboxTransactionContext transaction, CancellationToken cancellationToken = default)

    Inserts a single message into the outbox table atomically within the specified transaction.

    record: OutboxMessage
    The message to insert into the outbox.
    transaction: EricksonLopez.Outbox.Persistence.IOutboxTransactionContext
    The context representing the active database transaction.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • methodInsertBatchAsync
    public async ValueTask InsertBatchAsync(ReadOnlyMemory<OutboxMessage> records, EricksonLopez.Outbox.Persistence.IOutboxTransactionContext transaction, CancellationToken cancellationToken = default)

    Inserts a batch of messages into the outbox table in a single round-trip.

    records: ReadOnlyMemory<OutboxMessage>
    The batch of messages to insert.
    transaction: EricksonLopez.Outbox.Persistence.IOutboxTransactionContext
    The context representing the active database transaction.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Implementations should use bulk insert mechanisms (e.g., COPY, UNNEST, or table-valued parameters). If native bulk insert is unavailable, implementations fall back to individual inserts.

  • methodMarkAsDispatchedAsync
    public async ValueTask MarkAsDispatchedAsync(IReadOnlyList<OutboxMessage> messages, CancellationToken cancellationToken = default)

    Atomically marks the specified messages as successfully dispatched.

    messages: IReadOnlyList<OutboxMessage>
    The collection of messages to mark as dispatched.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • methodMarkAsFailedAsync
    public async ValueTask MarkAsFailedAsync(IReadOnlyList<OutboxMessage> messages, string error, bool isDeadLetter = false, CancellationToken cancellationToken = default)

    Marks the specified messages as failed, updating their error details and retry counts.

    messages: IReadOnlyList<OutboxMessage>
    The collection of messages that failed to process.
    error: string
    The error message or exception details causing the failure.
    isDeadLetter: bool
    `true` to mark the messages as permanently failed (dead letter); otherwise, `false`.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Is typically invoked by `Retry.RetryDispatcherInterceptor` when publishing fails. If the maximum retry attempts are exhausted, the message may be marked as a dead letter. Security Warning: The `error` parameter may contain sensitive information (such as connection strings in stack traces). Ensure exceptions are sanitized in production environments before they are persisted, to prevent leaking sensitive data.

  • methodPurgeDispatchedMessagesAsync
    public async ValueTask<int> PurgeDispatchedMessagesAsync(DateTimeOffset cutoff, int batchSize = 1000, CancellationToken cancellationToken = default)

    Purges dispatched messages that were processed prior to the specified cutoff timestamp. Used by `Hosting.OutboxCleanupService` when `DeleteOnDispatch = false`.

    cutoff: DateTimeOffset
    The cutoff timestamp; messages dispatched prior to this time will be deleted.
    batchSize: int
    The maximum number of rows to delete in a single batch.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation, returning the number of purged rows.

  • methodReclaimStaleMessagesAsync
    public async ValueTask<int> ReclaimStaleMessagesAsync(TimeSpan staleTimeout, CancellationToken cancellationToken = default)

    Reclaims messages that have remained in the InFlight state longer than the specified timeout.

    staleTimeout: TimeSpan
    The duration after which an InFlight message is considered abandoned.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the number of messages reclaimed.

    This mechanism prevents message loss if a dispatcher crashes after claiming a batch (transitioning from state 0 to 1) but before marking it as dispatched. Implementations must atomically reset these messages to the Pending state (0) if their last updated time is older than the current UTC time minus the stale timeout.

class

SqlServerOutboxSetup

Ensamblado: EricksonLopez.Outbox.Storage.SqlServer
public static class SqlServerOutboxSetup

Provides extension methods for configuring SQL Server outbox storage.

Miembros (1)

  • methodUseSqlServer
    public static OutboxOptions UseSqlServer(this OutboxOptions options, Func<IServiceProvider, IDbConnection> connectionFactory)

    Configures the outbox to use SQL Server as the storage engine using the provided connection factory.

    options: this OutboxOptions
    The outbox options being configured.
    connectionFactory: Func<IServiceProvider, IDbConnection>
    A factory delegate to provide an `IDbConnection` based on the `IServiceProvider`.

    Retorna: The original `OutboxOptions` for method chaining.

    Exceptions: ArgumentNullException: `options` or `connectionFactory` is `null`

EricksonLopez.Outbox.Storage.Sqlite#

4
class

SqliteDeadLetterRepository

Ensamblado: EricksonLopez.Outbox.Storage.Sqlite
public sealed class SqliteDeadLetterRepository : IDeadLetterRepository
Implementa: IDeadLetterRepository

Provides an SQLite implementation of `IDeadLetterRepository`.

Miembros (6)

  • constructorSqliteDeadLetterRepository
    public SqliteDeadLetterRepository(Func<IDbConnection> connectionFactory, IOptionsMonitor<OutboxRuntimeOptions> options)

    Initializes a new instance of the `SqliteDeadLetterRepository` class.

    connectionFactory: Func<IDbConnection>
    The factory that creates SQLite connections.
    options: IOptionsMonitor<OutboxRuntimeOptions>
    The outbox runtime options.

    Exceptions: ArgumentNullException: `connectionFactory` or `options` is `null`

  • methodDeleteAsync
    public async ValueTask DeleteAsync(Guid id, CancellationToken cancellationToken = default)

    Deletes a dead-lettered message by its unique identifier.

    id: Guid
    The unique identifier of the dead-lettered message to delete.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • methodGetAsync
    public async ValueTask<IReadOnlyList<DeadLetterMessage>> GetAsync(int limit = 100, DateTimeOffset? after = null, CancellationToken cancellationToken = default)

    Retrieves a page of dead-lettered messages for inspection or replay.

    limit: int
    The maximum number of records to return.
    after: DateTimeOffset?
    The cursor indicating to return records dead-lettered after this timestamp. Pass `DateTimeOffset.MinValue` for the first page.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the retrieved page of dead-lettered messages.

  • methodInsertAsync
    public async ValueTask InsertAsync(DeadLetterMessage message, IOutboxTransactionContext? transaction = default, CancellationToken cancellationToken = default)

    Persists a dead-lettered message.

    message: DeadLetterMessage
    The dead-lettered message to persist.
    transaction: IOutboxTransactionContext?
    The optional transaction context. If `null`, the repository must open its own connection and auto-commit the insert.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Called by the Dispatcher after a message has exhausted its `Retry.RetryPolicy`.

  • methodPurgeAsync
    public async ValueTask PurgeAsync(DateTimeOffset olderThan, CancellationToken cancellationToken = default)

    Purges all dead-lettered messages older than the specified timestamp.

    olderThan: DateTimeOffset
    The timestamp threshold; messages older than this value will be purged.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • propertyIsFirstPartyImplementation
    public bool IsFirstPartyImplementation { get; }

    Gets a value indicating whether this is a first-party (built-in) implementation.

    Used by `OutboxStartupValidator` to warn operators when a third-party `IDeadLetterRepository` is registered, reminding them to verify that their implementation correctly handles `transaction = null` (auto-commit mode). All first-party storage engine implementations override this to return `true`. Third-party implementations that do not override this will return `false`, triggering the startup advisory log message. This is a Zero-Reflection pattern: no `GetType().Name`, no string comparisons, no assembly scanning. The check is a simple virtual dispatch.

class

SqliteIdempotencyRepository

Ensamblado: EricksonLopez.Outbox.Storage.Sqlite
public sealed class SqliteIdempotencyRepository : IIdempotencyRepository
Implementa: IIdempotencyRepository

Provides an SQLite implementation of `IIdempotencyRepository`.

Miembros (3)

  • constructorSqliteIdempotencyRepository
    public SqliteIdempotencyRepository(Func<IDbConnection> connectionFactory, IOptionsMonitor<OutboxRuntimeOptions> options)

    Initializes a new instance of the `SqliteIdempotencyRepository` class.

    connectionFactory: Func<IDbConnection>
    The factory that creates SQLite connections.
    options: IOptionsMonitor<OutboxRuntimeOptions>
    The outbox runtime options.

    Exceptions: ArgumentNullException: `connectionFactory` or `options` is `null`

  • methodPurgeExpiredRecordsAsync
    public async ValueTask PurgeExpiredRecordsAsync(DateTimeOffset olderThan, CancellationToken cancellationToken = default)

    Purges idempotency records older than the specified timestamp.

    olderThan: DateTimeOffset
    The timestamp threshold; records older than this value will be purged.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Called periodically by `InboxCleanupService` to prevent table bloat.

  • methodTryInsertAsync
    public async ValueTask<bool> TryInsertAsync(IdempotencyRecord record, IOutboxTransactionContext? transaction = default, CancellationToken cancellationToken = default)

    Attempts to insert an idempotency record.

    record: IdempotencyRecord
    The idempotency record to insert.
    transaction: IOutboxTransactionContext?
    The optional transaction context.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result is `true` if the record was inserted; otherwise, `false` if the record already exists (duplicate).

class

SqliteOutboxRepository

Ensamblado: EricksonLopez.Outbox.Storage.Sqlite
public sealed class SqliteOutboxRepository : IOutboxRepository
Implementa: IOutboxRepository

Provides an SQLite-specific implementation of `IOutboxRepository`.

Miembros (9)

  • constructorSqliteOutboxRepository
    public SqliteOutboxRepository(Func<IDbConnection> connectionFactory, IOptions<OutboxRuntimeOptions>? options = null)

    Initializes a new instance of the `SqliteOutboxRepository` class.

    connectionFactory: Func<IDbConnection>
    The factory that creates SQLite connections.
    options: IOptions<OutboxRuntimeOptions>?
    The runtime options containing thresholds and configurations.

    Exceptions: ArgumentNullException: `connectionFactory` is `null`

  • methodFetchPendingAsync
    public async ValueTask<IReadOnlyList<OutboxMessage>> FetchPendingAsync(int batchSize, CancellationToken cancellationToken = default)

    Retrieves a batch of pending messages ready for delivery.

    batchSize: int
    The maximum number of messages to retrieve.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the batch of messages retrieved.

    The method fetches up to the specified batch size of messages that are in the Pending state (0) and whose delivery time is less than or equal to the current UTC time. Implementations guarantee safe concurrent polling by using SKIP LOCKED or equivalent semantics, atomically transitioning the fetched messages to the InFlight state (1). Scheduling edge case — `deliver_at` vs `MaxMessageAge`: Messages stored with a future `deliver_at` timestamp that exceeds `MaxMessageAge` will be silently excluded from polling by the `created_at` age guard. Such messages will not be processed and will not be automatically dead-lettered. Ensure `OutboxRuntimeOptions.MaxMessageAge` is greater than the maximum `deliver_at` offset used in your application (e.g., if scheduling up to 7 days ahead, set `MaxMessageAge ≥ 8 days`). Ordering with multiple dispatcher instances: When multiple dispatcher instances run concurrently, messages are fetched in `ORDER BY created_at ASC, id ASC` order but can be claimed by different instances via `SKIP LOCKED`, resulting in non-deterministic global ordering. In partitioned table setups, the order guarantee applies within each partition only. For strict global ordering, use a single dispatcher instance with `MaxDegreeOfParallelism = 1`.

  • methodGetPendingCountAsync
    public async ValueTask<long> GetPendingCountAsync(CancellationToken cancellationToken = default)

    Retrieves the approximate count of messages awaiting processing.

    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the approximate pending message count.

    Includes messages in the Pending (0) or Failed (3) states for metrics and monitoring.

  • methodInsertAsync
    public async ValueTask InsertAsync(OutboxMessage record, IOutboxTransactionContext transaction, CancellationToken cancellationToken = default)

    Inserts a single message into the outbox table atomically within the specified transaction.

    record: OutboxMessage
    The message to insert into the outbox.
    transaction: IOutboxTransactionContext
    The context representing the active database transaction.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • methodInsertBatchAsync
    public async ValueTask InsertBatchAsync(ReadOnlyMemory<OutboxMessage> records, IOutboxTransactionContext transaction, CancellationToken cancellationToken = default)

    Inserts a batch of messages into the outbox table in a single round-trip.

    records: ReadOnlyMemory<OutboxMessage>
    The batch of messages to insert.
    transaction: IOutboxTransactionContext
    The context representing the active database transaction.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Implementations should use bulk insert mechanisms (e.g., COPY, UNNEST, or table-valued parameters). If native bulk insert is unavailable, implementations fall back to individual inserts.

  • methodMarkAsDispatchedAsync
    public async ValueTask MarkAsDispatchedAsync(IReadOnlyList<OutboxMessage> messages, CancellationToken cancellationToken = default)

    Atomically marks the specified messages as successfully dispatched.

    messages: IReadOnlyList<OutboxMessage>
    The collection of messages to mark as dispatched.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • methodMarkAsFailedAsync
    public async ValueTask MarkAsFailedAsync(IReadOnlyList<OutboxMessage> messages, string error, bool isDeadLetter = false, CancellationToken cancellationToken = default)

    Marks the specified messages as failed, updating their error details and retry counts.

    messages: IReadOnlyList<OutboxMessage>
    The collection of messages that failed to process.
    error: string
    The error message or exception details causing the failure.
    isDeadLetter: bool
    `true` to mark the messages as permanently failed (dead letter); otherwise, `false`.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Is typically invoked by `Retry.RetryDispatcherInterceptor` when publishing fails. If the maximum retry attempts are exhausted, the message may be marked as a dead letter. Security Warning: The `error` parameter may contain sensitive information (such as connection strings in stack traces). Ensure exceptions are sanitized in production environments before they are persisted, to prevent leaking sensitive data.

  • methodPurgeDispatchedMessagesAsync
    public async ValueTask<int> PurgeDispatchedMessagesAsync(DateTimeOffset cutoff, int batchSize = 1000, CancellationToken cancellationToken = default)

    Purges dispatched messages that were processed prior to the specified cutoff timestamp. Used by `Hosting.OutboxCleanupService` when `DeleteOnDispatch = false`.

    cutoff: DateTimeOffset
    The cutoff timestamp; messages dispatched prior to this time will be deleted.
    batchSize: int
    The maximum number of rows to delete in a single batch.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation, returning the number of purged rows.

  • methodReclaimStaleMessagesAsync
    public async ValueTask<int> ReclaimStaleMessagesAsync(TimeSpan staleTimeout, CancellationToken cancellationToken = default)

    Reclaims messages that have remained in the InFlight state longer than the specified timeout.

    staleTimeout: TimeSpan
    The duration after which an InFlight message is considered abandoned.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the number of messages reclaimed.

    This mechanism prevents message loss if a dispatcher crashes after claiming a batch (transitioning from state 0 to 1) but before marking it as dispatched. Implementations must atomically reset these messages to the Pending state (0) if their last updated time is older than the current UTC time minus the stale timeout.

class

SqliteOutboxSetup

Ensamblado: EricksonLopez.Outbox.Storage.Sqlite
public static class SqliteOutboxSetup

Provides extension methods for configuring SQLite outbox storage.

Miembros (1)

  • methodUseSqlite
    public static OutboxOptions UseSqlite(this OutboxOptions options, Func<IServiceProvider, SqliteConnection> connectionFactory)

    Configures the outbox to use SQLite as the storage engine using the provided connection factory.

    options: this OutboxOptions
    The outbox options being configured.
    connectionFactory: Func<IServiceProvider, SqliteConnection>
    A factory delegate to provide a `SqliteConnection` based on the `IServiceProvider`.

    Retorna: The original `OutboxOptions` for method chaining.

    Exceptions: ArgumentNullException: `options` or `connectionFactory` is `null`

EricksonLopez.Outbox.Testing#

14
class

FakeBrokerPublisher

Ensamblado: EricksonLopez.Outbox
public sealed class FakeBrokerPublisher : IBrokerPublisher
Implementa: IBrokerPublisher

Provides a fake `IBrokerPublisher` implementation designed for use in unit and integration tests.

Notas:

This fake captures all published messages in memory, allowing you to assert that specific messages were dispatched during a test scenario without requiring a real message broker. Usage example:

var fakeBroker = new FakeBrokerPublisher();
// ... configure DI with fakeBroker
fakeBroker.ShouldHavePublished("order.created.v1").Once();

Miembros (8)

  • methodPublishAsync<T>
    public ValueTask<DispatchResult> PublishAsync<T>(MessageEnvelope<T> message, DispatchContext context) where T : notnull

    Inherits documentation from base type or interface.

    message: MessageEnvelope<T>
    context: DispatchContext
  • methodPublishBatchAsync<T>
    public async ValueTask<IReadOnlyList<DispatchResult>> PublishBatchAsync<T>(IReadOnlyList<MessageEnvelope<T>> messages, DispatchContext context) where T : notnull

    Inherits documentation from base type or interface.

    messages: IReadOnlyList<MessageEnvelope<T>>
    context: DispatchContext
  • methodPublishRawAsync
    public ValueTask<DispatchResult> PublishRawAsync(OutboxMessage message, OutboxMessageMetadata metadata, DispatchContext context)

    Publishes a raw serialized outbox message as-is.

    message: OutboxMessage
    The raw outbox message to publish.
    metadata: OutboxMessageMetadata
    The metadata associated with the message.
    context: DispatchContext
    The context governing the dispatch operation, including cancellation tokens.

    Retorna: A task that represents the asynchronous dispatch operation, containing the `DispatchResult`.

    Used by the Dispatcher which works with pre-serialized payloads, avoiding runtime generics and reflection for NativeAOT compatibility. DispatchResult contract for implementers: **Scenario**: **Return value**: - **Message published successfully**: **`DispatchResult.Ok()`**: - **Transient / recoverable failure (network timeout, broker unreachable, rate-limited)**: **`DispatchResult.FailAndRetry(exception)`**: - **Fatal / unrecoverable failure (schema mismatch, serialization error, message too large for broker, authorization denied)**: **`DispatchResult.FailFatal(exception)`**: Do NOT throw exceptions here. Thrown exceptions are treated as fatal failures by the dispatcher (equivalent to `DispatchResult.FailFatal`). Always catch broker exceptions and map them to the appropriate `DispatchResult`. Do NOT return `default(DispatchResult)`. The default value of the struct (`Success=false, ShouldRetry=false, Error=null`) is an invalid state that will cause the dispatcher to dead-letter the message with a misleading "no error" state. Always use one of the factory methods: `DispatchResult.Ok()`, `DispatchResult.FailAndRetry(ex)`, or `DispatchResult.FailFatal(ex)`. The dispatcher wraps calls to the publisher with a retry interceptor, which automatically retries `FailAndRetry` results with exponential backoff. Returning `FailFatal` bypasses retry and dead-letters the message immediately. OpenTelemetry — `messaging.system` tag requirement: The outbox core sets `messaging.system = "outbox"` as a default on the dispatch Activity. Broker implementers MUST override this tag with the actual broker name: `System.Diagnostics.Activity.Current?.SetTag("messaging.system", "rabbitmq"); // or "kafka", "azure_service_bus", etc.` This is required by the OpenTelemetry Messaging Semantic Conventions (v1.26+): https://opentelemetry.io/docs/specs/semconv/messaging/messaging-spans/#messaging-attributes

  • methodReset
    public void Reset()

    Clears all captured messages, resetting the state of the fake broker.

  • methodShouldHavePublished
    public IFakeBrokerAssertion ShouldHavePublished(string messageTypeAlias)

    Provides a fluent assertion to verify that a message matching the specified type alias was published.

    messageTypeAlias: string
    The string alias representing the message type.

    Retorna: An assertion interface to chain further constraints.

  • methodWithFailure
    public FakeBrokerPublisher WithFailure(Exception? ex = null)

    Configures the fake broker to simulate a failure result for subsequent publish calls.

    ex: Exception?
    The optional exception representing the failure. If not provided, a default `InvalidOperationException` is used.

    Retorna: The current `FakeBrokerPublisher` instance for chaining.

  • methodWithSuccess
    public FakeBrokerPublisher WithSuccess()

    Configures the fake broker to return successful results, resetting any previous failure simulations.

    Retorna: The current `FakeBrokerPublisher` instance for chaining.

  • propertyCapturedMessages
    public IReadOnlyList<PublishedRawMessage> CapturedMessages { get; }

    Gets all raw messages captured during the test execution.

class

FakeDeadLetterRepository

Ensamblado: EricksonLopez.Outbox
public sealed class FakeDeadLetterRepository : IDeadLetterRepository
Implementa: IDeadLetterRepository

Provides an in-memory implementation of `IDeadLetterRepository` for use in unit and integration tests.

Notas:

This implementation is thread-safe, utilizing a lock on its internal collection to support concurrent test scenarios.

Miembros (8)

  • methodClear
    public void Clear()

    Clears all messages from the repository. Useful for resetting state between test cases.

  • methodDeleteAsync
    public ValueTask DeleteAsync(Guid id, CancellationToken cancellationToken = default)

    Deletes a dead-lettered message by its unique identifier.

    id: Guid
    The unique identifier of the dead-lettered message to delete.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • methodGetAsync
    public ValueTask<IReadOnlyList<DeadLetterMessage>> GetAsync(int limit = 100, DateTimeOffset? after = null, CancellationToken cancellationToken = default)

    Retrieves a page of dead-lettered messages for inspection or replay.

    limit: int
    The maximum number of records to return.
    after: DateTimeOffset?
    The cursor indicating to return records dead-lettered after this timestamp. Pass `DateTimeOffset.MinValue` for the first page.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the retrieved page of dead-lettered messages.

  • methodInsertAsync
    public ValueTask InsertAsync(DeadLetterMessage message, IOutboxTransactionContext? transaction = default, CancellationToken cancellationToken = default)

    Persists a dead-lettered message.

    message: DeadLetterMessage
    The dead-lettered message to persist.
    transaction: IOutboxTransactionContext?
    The optional transaction context. If `null`, the repository must open its own connection and auto-commit the insert.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Gracefully handles `transaction` being null, as required by the contract.

  • methodPurgeAsync
    public ValueTask PurgeAsync(DateTimeOffset olderThan, CancellationToken cancellationToken = default)

    Purges all dead-lettered messages older than the specified timestamp.

    olderThan: DateTimeOffset
    The timestamp threshold; messages older than this value will be purged.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • propertyCount
    public int Count { get; }

    Gets the current count of dead-lettered messages in the repository.

  • propertyIsFirstPartyImplementation
    public bool IsFirstPartyImplementation { get; }

    Gets a value indicating whether this is a first-party (built-in) implementation.

    Used by `OutboxStartupValidator` to warn operators when a third-party `IDeadLetterRepository` is registered, reminding them to verify that their implementation correctly handles `transaction = null` (auto-commit mode). All first-party storage engine implementations override this to return `true`. Third-party implementations that do not override this will return `false`, triggering the startup advisory log message. This is a Zero-Reflection pattern: no `GetType().Name`, no string comparisons, no assembly scanning. The check is a simple virtual dispatch.

  • propertyMessages
    public IReadOnlyList<DeadLetterMessage> Messages { get; }

    Gets a snapshot of all dead-lettered messages currently stored in the repository.

class

FakeIdempotencyRepository

Ensamblado: EricksonLopez.Outbox
public sealed class FakeIdempotencyRepository : IIdempotencyRepository
Implementa: IIdempotencyRepository

Provides an in-memory implementation of `IIdempotencyRepository` for use in unit and integration tests.

Notas:

This implementation allows testing of consumers that use `InboxIdempotencyChecker` without requiring a real database. It uses a `ConcurrentDictionary<TKey, TValue>` keyed by `{messageId}:{consumerId}` to guarantee thread-safe, atomic insert-or-ignore semantics — matching the database-level `ON CONFLICT DO NOTHING` behavior. Usage example:

// In your test setup:
var fakeRepo = new FakeIdempotencyRepository();
var checker = new InboxIdempotencyChecker(fakeRepo);

// First call evaluates to true (should process):
var shouldProcess = await checker.ShouldProcessAsync("msg-1", "consumer-A", tx, ct);
Assert.True(shouldProcess);

// Second call evaluates to false (duplicate):
var duplicate = await checker.ShouldProcessAsync("msg-1", "consumer-A", tx, ct);
Assert.False(duplicate);

// Assert what was recorded:
Assert.Single(fakeRepo.Records);

Miembros (6)

  • methodClear
    public void Clear()

    Clears all records from the repository. Useful for resetting state between test cases.

  • methodPurgeExpiredRecordsAsync
    public ValueTask PurgeExpiredRecordsAsync(DateTimeOffset olderThan, CancellationToken cancellationToken = default)

    Purges idempotency records older than the specified timestamp.

    olderThan: DateTimeOffset
    The timestamp threshold; records older than this value will be purged.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Removes all records whose `IdempotencyRecord.ProcessedAt` is older than `olderThan`.

  • methodTryInsertAsync
    public ValueTask<bool> TryInsertAsync(IdempotencyRecord record, IOutboxTransactionContext? transaction = default, CancellationToken cancellationToken = default)

    Attempts to insert an idempotency record.

    record: IdempotencyRecord
    The idempotency record to insert.
    transaction: IOutboxTransactionContext?
    The optional transaction context.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result is `true` if the record was inserted; otherwise, `false` if the record already exists (duplicate).

    Uses `ConcurrentDictionary<TKey, TValue>.TryAdd` for atomic insert-or-ignore semantics. The `transaction` parameter is ignored in this in-memory implementation.

  • methodWasProcessed
    public bool WasProcessed(string messageId, string consumerId)

    Determines whether the specified message ID and consumer ID pair has already been processed.

    messageId: string
    The unique identifier of the message.
    consumerId: string
    The unique identifier of the consumer.

    Retorna: `true` if a record exists for the given pair; otherwise, `false`.

  • propertyCount
    public int Count { get; }

    Gets the current count of recorded idempotency entries.

  • propertyRecords
    public ICollection<IdempotencyRecord> Records { get; }

    Gets a snapshot of all idempotency records currently stored in the repository.

class

FakeInboxIdempotencyChecker

Ensamblado: EricksonLopez.Outbox
public sealed class FakeInboxIdempotencyChecker : IInboxIdempotencyChecker
Implementa: IInboxIdempotencyChecker

Provides a fake `IInboxIdempotencyChecker` implementation designed for use in unit and integration tests.

Notas:

This fake implementation delegates to a provided `FakeIdempotencyRepository` to simulate exactly-once processing behavior without requiring a real database connection.

Miembros (3)

  • constructorFakeInboxIdempotencyChecker
    public FakeInboxIdempotencyChecker(FakeIdempotencyRepository repository)

    Initializes a new instance of the `FakeInboxIdempotencyChecker` class.

    repository: FakeIdempotencyRepository
    The fake repository that stores and verify idempotency records.
  • methodShouldProcessAsync
    public async Task<bool> ShouldProcessAsync(string messageId, string consumerId, IOutboxTransactionContext transaction, CancellationToken cancellationToken = default)

    Determines whether a message should be processed by attempting to insert its idempotency record.

    messageId: string
    The unique identifier of the incoming message.
    consumerId: string
    The unique identifier of the consumer processing the message.
    transaction: IOutboxTransactionContext
    The active transaction context coordinating the idempotency check and the business operation.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: `true` if the record was successfully inserted and the message should be processed; otherwise, `false`.

    Transaction Isolation Note: Relies on the underlying database's atomic insert capabilities (e.g., ON CONFLICT DO NOTHING) to prevent race conditions (TOCTOU). This is completely safe under READ COMMITTED. However, if the provided `IOutboxTransactionContext` uses the `SERIALIZABLE` isolation level, concurrent inserts for the same message ID across different transactions may result in a serialization failure exception (e.g., SQL Server error 1205 or PostgreSQL 40001) instead of a graceful skip. Consumers using `SERIALIZABLE` must be prepared to catch and retry these specific transaction abort exceptions at the application level.

  • methodShouldSkipAsync
    public async Task<bool> ShouldSkipAsync(Guid messageId, IOutboxTransactionContext transaction, string consumerId = OutboxConstants.DispatcherConsumerId, CancellationToken cancellationToken = default)

    Determines whether a specific message has already been processed and should be skipped.

    messageId: Guid
    The unique identifier of the message.
    transaction: IOutboxTransactionContext
    The active transaction context coordinating the check.
    consumerId: string
    A unique, stable identifier for the consumer performing the check. Defaults to `OutboxConstants.DispatcherConsumerId` for dispatcher-internal use. Provide a consumer-specific ID (e.g., `"order-service.payment-handler"`) when calling from user-facing consumers.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: `true` if the message has already been processed; otherwise, `false`.

    Uses a database insert to atomically detect duplicates. The `consumerId` identifies which consumer is performing the check. Always use a unique, stable consumer ID per consumer in your application to avoid collision with other consumers' records. Warning: Do not reuse `OutboxConstants.DispatcherConsumerId` in your own consumers. That ID is reserved for the outbox dispatcher's internal deduplication. Reusing it would cause your consumer's records to collide with the dispatcher's, resulting in incorrect duplicate-detection behavior.

class

FakeOutboxDispatcher

Ensamblado: EricksonLopez.Outbox
public sealed class FakeOutboxDispatcher

Provides a fake outbox dispatcher implementation for use in unit and integration tests.

Notas:

This dispatcher captures dispatch requests and provides fluent assertions to verify that the correct messages were dispatched. It can be used to simulate the background dispatcher behavior without requiring a running background service, verifying that the dispatcher correctly invokes the configured broker publisher after messages are stored.

Miembros (6)

  • constructorFakeOutboxDispatcher
    public FakeOutboxDispatcher(FakeBrokerPublisher broker, IOutboxRepository? repository = null)

    Initializes a new instance of the `FakeOutboxDispatcher` class.

    broker: FakeBrokerPublisher
    The fake broker publisher that captures published messages.
    repository: IOutboxRepository?
    An optional repository that fetches pending messages and mark them as dispatched.

    Exceptions: ArgumentNullException: `broker` is `null`

  • methodDispatchAsync
    public async Task<int> DispatchAsync(IReadOnlyList<OutboxMessage>? messages = null, CancellationToken cancellationToken = default)

    Manually triggers the dispatch process for all pending messages.

    messages: IReadOnlyList<OutboxMessage>?
    An optional explicit list of messages to dispatch.
    cancellationToken: CancellationToken
    A token that can be used to cancel the dispatch operation.

    Retorna: A task that represents the asynchronous dispatch operation. The task result contains the number of messages successfully dispatched.

    If an explicit list of `messages` is provided, only those messages are dispatched. Otherwise, if a repository is configured, it fetches all pending messages from the repository and dispatches them.

  • methodReset
    public void Reset()

    Clears the captured list of dispatched messages, resetting the state of the fake dispatcher.

  • methodShouldHaveDispatched
    public void ShouldHaveDispatched(int count)

    Asserts that exactly the specified number of messages were successfully dispatched.

    count: int
    The exact number of messages expected to have been dispatched.

    Exceptions: InvalidOperationException: Thrown when the actual number of dispatched messages does not match the expected count

  • methodShouldHaveDispatchedNothing
    public void ShouldHaveDispatchedNothing()

    Asserts that no messages were dispatched during the test.

    Exceptions: InvalidOperationException: Thrown when one or more messages were dispatched

  • propertyDispatchedMessages
    public IReadOnlyList<OutboxMessage> DispatchedMessages { get; }

    Gets a read-only list of all messages that were successfully dispatched during the test.

class

FakeOutboxRepository

Ensamblado: EricksonLopez.Outbox
public sealed class FakeOutboxRepository : IOutboxRepository
Implementa: IOutboxRepository

Provides a test double for `IOutboxRepository` that stores outbox messages in memory.

Notas:

This type is a discoverable, named test double following the established `Fake*` naming convention alongside `FakeBrokerPublisher`, `FakeDeadLetterRepository`, and `FakeIdempotencyRepository`. Use this type when testing dispatcher background services, retry logic, or any component that depends on `IOutboxRepository` directly. For testing the `IOutbox` producer side, prefer `InMemoryOutboxStore` instead. State inspection: Access `Inner` to inspect pending, in-flight, dispatched, and failed message collections after exercising the dispatcher under test. Example:

var fakeRepo = new FakeOutboxRepository();
services.AddSingleton<IOutboxRepository>(fakeRepo);

// After test:
var pending = fakeRepo.Inner.GetPending();
Assert.Equal(0, pending.Count);

Miembros (10)

  • methodFetchPendingAsync
    public ValueTask<IReadOnlyList<OutboxMessage>> FetchPendingAsync(int batchSize, CancellationToken cancellationToken = default)

    Retrieves a batch of pending messages ready for delivery.

    batchSize: int
    The maximum number of messages to retrieve.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the batch of messages retrieved.

    The method fetches up to the specified batch size of messages that are in the Pending state (0) and whose delivery time is less than or equal to the current UTC time. Implementations guarantee safe concurrent polling by using SKIP LOCKED or equivalent semantics, atomically transitioning the fetched messages to the InFlight state (1). Scheduling edge case — `deliver_at` vs `MaxMessageAge`: Messages stored with a future `deliver_at` timestamp that exceeds `MaxMessageAge` will be silently excluded from polling by the `created_at` age guard. Such messages will not be processed and will not be automatically dead-lettered. Ensure `OutboxRuntimeOptions.MaxMessageAge` is greater than the maximum `deliver_at` offset used in your application (e.g., if scheduling up to 7 days ahead, set `MaxMessageAge ≥ 8 days`). Ordering with multiple dispatcher instances: When multiple dispatcher instances run concurrently, messages are fetched in `ORDER BY created_at ASC, id ASC` order but can be claimed by different instances via `SKIP LOCKED`, resulting in non-deterministic global ordering. In partitioned table setups, the order guarantee applies within each partition only. For strict global ordering, use a single dispatcher instance with `MaxDegreeOfParallelism = 1`.

  • methodGetMessageAsync
    public ValueTask<OutboxMessage?> GetMessageAsync(Guid id, CancellationToken cancellationToken = default)

    Retrieves a single outbox message by its unique identifier, regardless of its current state.

    id: Guid
    The unique identifier of the message to retrieve.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: The `OutboxMessage` with the specified `id`, or `null` if no message with that ID exists in the outbox table.

    AUDIT-FIX P1-G — Default Interface Method for operational tooling: Designed for debugging, manual requeue, and administrative UIs that need to inspect a specific message. It is not used in the normal dispatcher hot path. This is a Default Interface Method (DIM): existing implementations automatically inherit the default implementation which throws `NotSupportedException`. Storage engine implementations should override `GetMessageAsync(Guid, CancellationToken)` for efficient single-row lookup. For PostgreSQL, the expected implementation is: `SELECT * FROM outbox.messages WHERE id = @Id LIMIT 1;`

  • methodGetPendingCountAsync
    public ValueTask<long> GetPendingCountAsync(CancellationToken cancellationToken = default)

    Retrieves the approximate count of messages awaiting processing.

    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the approximate pending message count.

    Includes messages in the Pending (0) or Failed (3) states for metrics and monitoring.

  • methodInsertAsync
    public ValueTask InsertAsync(OutboxMessage record, IOutboxTransactionContext transaction, CancellationToken cancellationToken = default)

    Inserts a single message into the outbox table atomically within the specified transaction.

    record: OutboxMessage
    The message to insert into the outbox.
    transaction: IOutboxTransactionContext
    The context representing the active database transaction.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • methodInsertBatchAsync
    public ValueTask InsertBatchAsync(ReadOnlyMemory<OutboxMessage> records, IOutboxTransactionContext transaction, CancellationToken cancellationToken = default)

    Inserts a batch of messages into the outbox table in a single round-trip.

    records: ReadOnlyMemory<OutboxMessage>
    The batch of messages to insert.
    transaction: IOutboxTransactionContext
    The context representing the active database transaction.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Implementations should use bulk insert mechanisms (e.g., COPY, UNNEST, or table-valued parameters). If native bulk insert is unavailable, implementations fall back to individual inserts.

  • methodMarkAsDispatchedAsync
    public ValueTask MarkAsDispatchedAsync(IReadOnlyList<OutboxMessage> messages, CancellationToken cancellationToken = default)

    Atomically marks the specified messages as successfully dispatched.

    messages: IReadOnlyList<OutboxMessage>
    The collection of messages to mark as dispatched.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • methodMarkAsFailedAsync
    public ValueTask MarkAsFailedAsync(IReadOnlyList<OutboxMessage> messages, string error, bool isDeadLetter = false, CancellationToken cancellationToken = default)

    Marks the specified messages as failed, updating their error details and retry counts.

    messages: IReadOnlyList<OutboxMessage>
    The collection of messages that failed to process.
    error: string
    The error message or exception details causing the failure.
    isDeadLetter: bool
    `true` to mark the messages as permanently failed (dead letter); otherwise, `false`.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Is typically invoked by `Retry.RetryDispatcherInterceptor` when publishing fails. If the maximum retry attempts are exhausted, the message may be marked as a dead letter. Security Warning: The `error` parameter may contain sensitive information (such as connection strings in stack traces). Ensure exceptions are sanitized in production environments before they are persisted, to prevent leaking sensitive data.

  • methodPurgeDispatchedMessagesAsync
    public ValueTask<int> PurgeDispatchedMessagesAsync(DateTimeOffset cutoff, int batchSize = 1000, CancellationToken cancellationToken = default)

    Purges dispatched messages that were processed prior to the specified cutoff timestamp. Used by `Hosting.OutboxCleanupService` when `DeleteOnDispatch = false`.

    cutoff: DateTimeOffset
    The cutoff timestamp; messages dispatched prior to this time will be deleted.
    batchSize: int
    The maximum number of rows to delete in a single batch.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation, returning the number of purged rows.

  • methodReclaimStaleMessagesAsync
    public ValueTask<int> ReclaimStaleMessagesAsync(TimeSpan staleTimeout, CancellationToken cancellationToken = default)

    Reclaims messages that have remained in the InFlight state longer than the specified timeout.

    staleTimeout: TimeSpan
    The duration after which an InFlight message is considered abandoned.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the number of messages reclaimed.

    This mechanism prevents message loss if a dispatcher crashes after claiming a batch (transitioning from state 0 to 1) but before marking it as dispatched. Implementations must atomically reset these messages to the Pending state (0) if their last updated time is older than the current UTC time minus the stale timeout.

  • propertyInner
    public InMemoryOutboxStoreRepository Inner { get; }

    Gets the underlying `InMemoryOutboxStoreRepository` for state inspection in tests.

interface

IFakeBrokerAssertion

Ensamblado: EricksonLopez.Outbox
public interface IFakeBrokerAssertion

Defines a fluent assertion interface for verifying messages published to the fake broker.

Miembros (5)

  • methodAtLeastOnce
    void AtLeastOnce()

    Asserts that the matching message was published at least once.

  • methodNever
    void Never()

    Asserts that the matching message was never published.

  • methodOnce
    void Once()

    Asserts that the matching message was published exactly once.

  • methodTimes
    void Times(int count)

    Asserts that the matching message was published exactly the specified number of times.

    count: int
    The exact number of times the message should have been published.
  • methodWithCorrelationId
    IFakeBrokerAssertion WithCorrelationId(string correlationId)

    Constrains the assertion to match only messages with the specified correlation ID.

    correlationId: string
    The correlation ID to filter by.

    Retorna: The current assertion interface for chaining.

interface

IOutboxAssertion<TMessage>

Ensamblado: EricksonLopez.Outbox
public interface IOutboxAssertion<TMessage>

Defines an interface for chaining fluid assertions on a published outbox message of a specific type.

Notas:

Type parameters: TMessage: The type of the message being asserted.

Miembros (5)

  • methodAtLeastOnce
    void AtLeastOnce()

    Asserts that the matching message was published at least once.

  • methodNever
    void Never()

    Asserts that the matching message was never published.

  • methodOnce
    void Once()

    Asserts that the matching message was published exactly once.

  • methodTimes
    void Times(int count)

    Asserts that the matching message was published exactly the specified number of times.

    count: int
    The exact number of times the message should have been published.
  • methodWithCondition
    IOutboxAssertion<TMessage> WithCondition(Func<TMessage, bool> predicate)

    Applies a predicate condition to constrain the assertion to matching message payloads.

    predicate: Func<TMessage, bool>
    A function to test each message payload for a condition.

    Retorna: The current assertion interface for chaining.

interface

IOutboxTester

Ensamblado: EricksonLopez.Outbox
public interface IOutboxTester

Defines a fluent assertion interface to verify that domain events were correctly published to the Outbox.

Notas:

Allows for expressive, robust tests that verify outbox side effects without relying on brittle mocking framework verifications (e.g., `Mock.Verify()`).

Miembros (1)

  • methodShouldHavePublished<TMessage>
    IOutboxAssertion<TMessage> ShouldHavePublished<TMessage>() where TMessage : notnull

    Asserts that an event of the specified type was published to the outbox.

    Retorna: A fluent assertion builder to chain further conditions (e.g., payload assertions or expected occurrences).

    Type parameters: TMessage: The type of the message to assert on.

class

InMemoryOutboxStore

Ensamblado: EricksonLopez.Outbox
public sealed class InMemoryOutboxStore : IOutbox
Implementa: IOutbox

Provides a thread-safe, in-memory implementation of `IOutbox` for use in unit tests.

Notas:

This store captures all stored messages in memory, enabling assertions via `GetPublishedMessages<TMessage>`. It avoids the need for mocking frameworks when testing the publisher side of the outbox pattern.

Miembros (6)

  • methodGetPublishedMessages<TMessage>
    public IReadOnlyList<TMessage> GetPublishedMessages<TMessage>() where TMessage : notnull

    Retrieves a read-only list of all stored messages that match the specified type `TMessage`.

    Retorna: A list containing the matching messages.

    Type parameters: TMessage: The type of the messages to retrieve.

  • methodPublish<TMessage>
    public OutboxMessageBuilder<TMessage> Publish<TMessage>(TMessage message) where TMessage : notnull

    Begins a fluent message-building chain for enriching a message before persisting it to this in-memory store.

    message: TMessage
    The initial message payload to begin enriching.

    Retorna: A fluent builder instance to configure transaction, delay, and metadata.

    Type parameters: TMessage: The type of the message being built.

  • methodReset
    public void Reset()

    Clears all captured messages from the store, resetting its state.

  • methodStoreAsync<TMessage>
    public ValueTask StoreAsync<TMessage>(ReadOnlyMemory<TMessage> messages, IOutboxTransactionContext transaction, CancellationToken cancellationToken = default) where TMessage : notnull

    Stores a single message atomically within the specified transaction.

    messages: ReadOnlyMemory<TMessage>
    transaction: IOutboxTransactionContext
    The transaction context that scopes this operation.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A `ValueTask` representing the asynchronous store operation.

    Payload and header size limits are enforced at serialization time. If the serialized payload exceeds `OutboxRuntimeOptions.MaxPayloadSizeInBytes`, an `OutboxPayloadTooLargeException` is thrown. If serialized headers exceed `OutboxRuntimeOptions.MaxHeaderSizeInBytes`, an `OutboxHeadersTooLargeException` is thrown. Both exception types are defined in `EricksonLopez.Outbox.dll`. Type parameters: TMessage: The type of the message to store. Exceptions: ArgumentNullException: Thrown when `transaction` is `null`; System.InvalidOperationException: Thrown if the message type alias is not registered and `OutboxRuntimeOptions.ThrowOnUnregisteredType` is `true` (`OutboxTypeNotRegisteredException`, a subtype of `OutboxException`)

  • methodStoreAsync<TMessage>
    public ValueTask StoreAsync<TMessage>(TMessage message, IOutboxTransactionContext transaction, CancellationToken cancellationToken = default) where TMessage : notnull

    Stores a single message atomically within the specified transaction.

    message: TMessage
    The message payload to store in the outbox.
    transaction: IOutboxTransactionContext
    The transaction context that scopes this operation.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A `ValueTask` representing the asynchronous store operation.

    Payload and header size limits are enforced at serialization time. If the serialized payload exceeds `OutboxRuntimeOptions.MaxPayloadSizeInBytes`, an `OutboxPayloadTooLargeException` is thrown. If serialized headers exceed `OutboxRuntimeOptions.MaxHeaderSizeInBytes`, an `OutboxHeadersTooLargeException` is thrown. Both exception types are defined in `EricksonLopez.Outbox.dll`. Type parameters: TMessage: The type of the message to store. Exceptions: ArgumentNullException: Thrown when `transaction` is `null`; System.InvalidOperationException: Thrown if the message type alias is not registered and `OutboxRuntimeOptions.ThrowOnUnregisteredType` is `true` (`OutboxTypeNotRegisteredException`, a subtype of `OutboxException`)

  • methodStoreAsync<TMessage>
    public ValueTask StoreAsync<TMessage>(TMessage message, IOutboxTransactionContext transaction, OutboxMessageMetadata metadata, DateTimeOffset? deliverAt, CancellationToken cancellationToken = default) where TMessage : notnull

    Stores a single message with explicit metadata and scheduling atomically within the specified transaction.

    message: TMessage
    The message payload to store in the outbox.
    transaction: IOutboxTransactionContext
    The transaction context that scopes this operation.
    metadata: OutboxMessageMetadata
    The metadata associated with the message, such as correlation or causation IDs.
    deliverAt: DateTimeOffset?
    An optional future timestamp indicating when the message should become visible for dispatching.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A `ValueTask` representing the asynchronous storage operation.

    Payload and header size limits are enforced at serialization time. If the serialized payload exceeds `OutboxRuntimeOptions.MaxPayloadSizeInBytes`, an `OutboxPayloadTooLargeException` is thrown. If serialized headers exceed `OutboxRuntimeOptions.MaxHeaderSizeInBytes`, an `OutboxHeadersTooLargeException` is thrown. Both exception types are defined in `EricksonLopez.Outbox.dll`. Type parameters: TMessage: The type of the message to store. Exceptions: ArgumentNullException: Thrown when `transaction` is `null`

class

InMemoryOutboxStoreRepository

Ensamblado: EricksonLopez.Outbox
public sealed class InMemoryOutboxStoreRepository : IOutboxRepository
Implementa: IOutboxRepository

Provides a non-generic, in-memory implementation of `IOutboxRepository`.

Notas:

This repository simulates a real database-backed repository without performing any I/O operations, making it ideal for testing dispatcher background services and related infrastructure.

Miembros (15)

  • constructorInMemoryOutboxStoreRepository
    public InMemoryOutboxStoreRepository(TimeProvider? timeProvider = null)

    Initializes a new instance of the `InMemoryOutboxStoreRepository` class.

    timeProvider: TimeProvider?
    Optional time provider for deterministic time manipulation in tests.
  • methodFetchPendingAsync
    public ValueTask<IReadOnlyList<OutboxMessage>> FetchPendingAsync(int batchSize, CancellationToken cancellationToken = default)

    Retrieves a batch of pending messages ready for delivery.

    batchSize: int
    The maximum number of messages to retrieve.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the batch of messages retrieved.

    The method fetches up to the specified batch size of messages that are in the Pending state (0) and whose delivery time is less than or equal to the current UTC time. Implementations guarantee safe concurrent polling by using SKIP LOCKED or equivalent semantics, atomically transitioning the fetched messages to the InFlight state (1). Scheduling edge case — `deliver_at` vs `MaxMessageAge`: Messages stored with a future `deliver_at` timestamp that exceeds `MaxMessageAge` will be silently excluded from polling by the `created_at` age guard. Such messages will not be processed and will not be automatically dead-lettered. Ensure `OutboxRuntimeOptions.MaxMessageAge` is greater than the maximum `deliver_at` offset used in your application (e.g., if scheduling up to 7 days ahead, set `MaxMessageAge ≥ 8 days`). Ordering with multiple dispatcher instances: When multiple dispatcher instances run concurrently, messages are fetched in `ORDER BY created_at ASC, id ASC` order but can be claimed by different instances via `SKIP LOCKED`, resulting in non-deterministic global ordering. In partitioned table setups, the order guarantee applies within each partition only. For strict global ordering, use a single dispatcher instance with `MaxDegreeOfParallelism = 1`.

  • methodGetDispatched
    public IReadOnlyList<OutboxMessage> GetDispatched()

    Retrieves a list of all messages that have been marked as successfully dispatched.

    Retorna: A read-only list of dispatched outbox messages.

  • methodGetFailed
    public IReadOnlyList<OutboxMessage> GetFailed()

    Retrieves a list of all messages that have been marked as failed.

    Retorna: A read-only list of failed outbox messages.

  • methodGetInFlight
    public IReadOnlyList<OutboxMessage> GetInFlight()

    Retrieves a list of all messages that are currently in-flight (being processed).

    Retorna: A read-only list of in-flight outbox messages.

  • methodGetMessageAsync
    public ValueTask<OutboxMessage?> GetMessageAsync(Guid id, CancellationToken cancellationToken = default)

    Retrieves a single outbox message by its unique identifier, regardless of its current state.

    id: Guid
    The unique identifier of the message to retrieve.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: The `OutboxMessage` with the specified `id`, or `null` if no message with that ID exists in the outbox table.

    In-memory implementation: searches all state buckets (pending, in-flight, dispatched, failed) since the InMemory store maintains the full message lifecycle. Returns null if the message is not found in any bucket.

  • methodGetPending
    public IReadOnlyList<OutboxMessage> GetPending()

    Retrieves a list of all messages currently residing in the pending queue.

    Retorna: A read-only list of pending outbox messages.

  • methodGetPendingCountAsync
    public ValueTask<long> GetPendingCountAsync(CancellationToken cancellationToken = default)

    Retrieves the approximate count of messages awaiting processing.

    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the approximate pending message count.

    Includes messages in the Pending (0) or Failed (3) states for metrics and monitoring.

  • methodInsertAsync
    public ValueTask InsertAsync(OutboxMessage record, IOutboxTransactionContext transaction, CancellationToken cancellationToken = default)

    Inserts a single message into the outbox table atomically within the specified transaction.

    record: OutboxMessage
    The message to insert into the outbox.
    transaction: IOutboxTransactionContext
    The context representing the active database transaction.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • methodInsertBatchAsync
    public ValueTask InsertBatchAsync(ReadOnlyMemory<OutboxMessage> records, IOutboxTransactionContext transaction, CancellationToken cancellationToken = default)

    Inserts a batch of messages into the outbox table in a single round-trip.

    records: ReadOnlyMemory<OutboxMessage>
    The batch of messages to insert.
    transaction: IOutboxTransactionContext
    The context representing the active database transaction.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Implementations should use bulk insert mechanisms (e.g., COPY, UNNEST, or table-valued parameters). If native bulk insert is unavailable, implementations fall back to individual inserts.

  • methodMarkAsDispatchedAsync
    public ValueTask MarkAsDispatchedAsync(IReadOnlyList<OutboxMessage> messages, CancellationToken cancellationToken = default)

    Atomically marks the specified messages as successfully dispatched.

    messages: IReadOnlyList<OutboxMessage>
    The collection of messages to mark as dispatched.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • methodMarkAsFailedAsync
    public ValueTask MarkAsFailedAsync(IReadOnlyList<OutboxMessage> messages, string error, bool isDeadLetter = false, CancellationToken cancellationToken = default)

    Marks the specified messages as failed, updating their error details and retry counts.

    messages: IReadOnlyList<OutboxMessage>
    The collection of messages that failed to process.
    error: string
    The error message or exception details causing the failure.
    isDeadLetter: bool
    `true` to mark the messages as permanently failed (dead letter); otherwise, `false`.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Is typically invoked by `Retry.RetryDispatcherInterceptor` when publishing fails. If the maximum retry attempts are exhausted, the message may be marked as a dead letter. Security Warning: The `error` parameter may contain sensitive information (such as connection strings in stack traces). Ensure exceptions are sanitized in production environments before they are persisted, to prevent leaking sensitive data.

  • methodPurgeDispatchedMessagesAsync
    public ValueTask<int> PurgeDispatchedMessagesAsync(DateTimeOffset cutoff, int batchSize = 1000, CancellationToken cancellationToken = default)

    Purges dispatched messages that were processed prior to the specified cutoff timestamp. Used by `Hosting.OutboxCleanupService` when `DeleteOnDispatch = false`.

    cutoff: DateTimeOffset
    The cutoff timestamp; messages dispatched prior to this time will be deleted.
    batchSize: int
    The maximum number of rows to delete in a single batch.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation, returning the number of purged rows.

  • methodReclaimStaleMessagesAsync
    public ValueTask<int> ReclaimStaleMessagesAsync(TimeSpan staleTimeout, CancellationToken cancellationToken = default)

    Reclaims messages that have remained in the InFlight state longer than the specified timeout.

    staleTimeout: TimeSpan
    The duration after which an InFlight message is considered abandoned.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the number of messages reclaimed.

    This mechanism prevents message loss if a dispatcher crashes after claiming a batch (transitioning from state 0 to 1) but before marking it as dispatched. Implementations must atomically reset these messages to the Pending state (0) if their last updated time is older than the current UTC time minus the stale timeout.

  • methodReset
    public void Reset()

    Clears all state across the pending, dispatched, and failed collections.

class

OutboxTesterImpl

Ensamblado: EricksonLopez.Outbox
public sealed class OutboxTesterImpl : IOutboxTester
Implementa: IOutboxTester

Provides a concrete implementation of `IOutboxTester` backed by an `InMemoryOutboxStore`.

Miembros (2)

  • constructorOutboxTesterImpl
    public OutboxTesterImpl(InMemoryOutboxStore store)

    Initializes a new instance of the `OutboxTesterImpl` class.

    store: InMemoryOutboxStore
    The in-memory outbox store that collects published messages.

    Exceptions: ArgumentNullException: `store` is `null`

  • methodShouldHavePublished<TMessage>
    public IOutboxAssertion<TMessage> ShouldHavePublished<TMessage>() where TMessage : notnull

    Asserts that an event of the specified type was published to the outbox.

    Retorna: A fluent assertion builder to chain further conditions (e.g., payload assertions or expected occurrences).

    Type parameters: TMessage: The type of the message to assert on.

record

PublishedRawMessage

Ensamblado: EricksonLopez.Outbox
public sealed record PublishedRawMessage(string MessageType, ReadOnlyMemory<byte> Payload, OutboxMessageMetadata Metadata)

Represents a raw message that was published and captured by the fake broker.

Miembros (4)

  • constructorPublishedRawMessage
    public PublishedRawMessage(string MessageType, ReadOnlyMemory<byte> Payload, OutboxMessageMetadata Metadata)

    Initializes a new instance of PublishedRawMessage.

    MessageType: string
    The string alias of the message type.
    Payload: ReadOnlyMemory<byte>
    The raw serialized payload of the message.
    Metadata: OutboxMessageMetadata
    The metadata associated with the message.
  • propertyMessageType
    public string MessageType { get; init; }

    The string alias of the message type.

  • propertyMetadata
    public OutboxMessageMetadata Metadata { get; init; }

    The metadata associated with the message.

  • propertyPayload
    public ReadOnlyMemory<byte> Payload { get; init; }

    The raw serialized payload of the message.

class

TestingOutboxExtensions

Ensamblado: EricksonLopez.Outbox
public static class TestingOutboxExtensions

Extension methods that add fluent, expressive assertion helpers for outbox-based tests. These extensions bridge `IOutboxTester` and `InMemoryOutboxStore` to provide a high-signal, low-ceremony testing API without requiring a mocking framework.

Notas:

Example:

// Setup
var store = new InMemoryOutboxStore();
services.AddSingleton<IOutbox>(store);
var tester = new OutboxTesterImpl(store);

// Act
await sut.DoSomethingAsync();

// Assert
tester.ShouldHavePublished<OrderCreatedEvent>()
      .WithCondition(e => e.OrderId == expectedId)
      .Once();

// Or using the shorthand extensions:
store.ShouldHavePublished<OrderCreatedEvent>(e => e.OrderId == expectedId);
store.ShouldHavePublishedOnce<OrderCreatedEvent>();
store.ShouldNotHavePublished<OrderCancelledEvent>();

Miembros (13)

  • methodShouldHavePublished<TMessage>
    public static void ShouldHavePublished<TMessage>(this IOutboxTester tester, Func<TMessage, bool> predicate) where TMessage : notnull

    Asserts that at least one message of type `TMessage` was published matching the given predicate.

    tester: this IOutboxTester
    The outbox tester instance.
    predicate: Func<TMessage, bool>
    A predicate to filter matching messages.

    Type parameters: TMessage: The type of the message to assert on.

  • methodShouldHavePublished<TMessage>
    public static IReadOnlyList<TMessage> ShouldHavePublished<TMessage>(this InMemoryOutboxStore store) where TMessage : notnull

    Asserts that at least one message of type `TMessage` was stored.

    store: this InMemoryOutboxStore
    The in-memory outbox store.

    Retorna: All stored messages of that type for further inspection.

    Type parameters: TMessage: The type of the message to assert on. Exceptions: InvalidOperationException: Thrown when no messages of the type were found

  • methodShouldHavePublished<TMessage>
    public static IReadOnlyList<TMessage> ShouldHavePublished<TMessage>(this InMemoryOutboxStore store, Func<TMessage, bool> predicate) where TMessage : notnull

    Asserts that at least one message of type `TMessage` was stored and that at least one message matches the given predicate.

    store: this InMemoryOutboxStore
    The in-memory outbox store.
    predicate: Func<TMessage, bool>
    A predicate to filter matching messages.

    Retorna: All stored messages of that type that match the predicate.

    Type parameters: TMessage: The type of the message to assert on.

  • methodShouldHavePublishedOnce<TMessage>
    public static void ShouldHavePublishedOnce<TMessage>(this IOutboxTester tester) where TMessage : notnull

    Asserts that exactly one message of type `TMessage` was published. Syntactic sugar over `IOutboxAssertion<TMessage>.Once`.

    tester: this IOutboxTester
    The outbox tester instance.

    Type parameters: TMessage: The type of the message to assert on.

  • methodShouldHavePublishedOnce<TMessage>
    public static void ShouldHavePublishedOnce<TMessage>(this IOutboxTester tester, Func<TMessage, bool> predicate) where TMessage : notnull

    Asserts that exactly one message of type `TMessage` matching the given predicate was published.

    tester: this IOutboxTester
    The outbox tester instance.
    predicate: Func<TMessage, bool>
    A predicate to filter matching messages.

    Type parameters: TMessage: The type of the message to assert on.

  • methodShouldHavePublishedOnce<TMessage>
    public static TMessage ShouldHavePublishedOnce<TMessage>(this InMemoryOutboxStore store) where TMessage : notnull

    Asserts that exactly one message of type `TMessage` was stored.

    store: this InMemoryOutboxStore
    The in-memory outbox store.

    Retorna: The single published message.

    Type parameters: TMessage: The type of the message to assert on. Exceptions: InvalidOperationException: Thrown when the count is not exactly 1

  • methodShouldHavePublishedOnce<TMessage>
    public static TMessage ShouldHavePublishedOnce<TMessage>(this InMemoryOutboxStore store, Func<TMessage, bool> predicate) where TMessage : notnull

    Asserts that exactly one message of type `TMessage` matching the given predicate was stored.

    store: this InMemoryOutboxStore
    The in-memory outbox store.
    predicate: Func<TMessage, bool>
    A predicate to filter matching messages.

    Retorna: The single matching message.

    Type parameters: TMessage: The type of the message to assert on.

  • methodShouldHavePublishedTimes<TMessage>
    public static void ShouldHavePublishedTimes<TMessage>(this IOutboxTester tester, int times) where TMessage : notnull

    Asserts that exactly `times` messages of type `TMessage` were published.

    tester: this IOutboxTester
    The outbox tester instance.
    times: int
    The expected occurrence count.

    Type parameters: TMessage: The type of the message to assert on.

  • methodShouldHavePublishedTimes<TMessage>
    public static IReadOnlyList<TMessage> ShouldHavePublishedTimes<TMessage>(this InMemoryOutboxStore store, int count) where TMessage : notnull

    Asserts that exactly `count` messages of type `TMessage` were stored.

    store: this InMemoryOutboxStore
    The in-memory outbox store.
    count: int
    The expected number of published messages.

    Retorna: All stored messages of that type.

    Type parameters: TMessage: The type of the message to assert on.

  • methodShouldNotHavePublished<TMessage>
    public static void ShouldNotHavePublished<TMessage>(this IOutboxTester tester) where TMessage : notnull

    Asserts that no messages of type `TMessage` were published. Syntactic sugar over `IOutboxAssertion<TMessage>.Never`.

    tester: this IOutboxTester
    The outbox tester instance.

    Type parameters: TMessage: The type of the message to assert on. Example: `tester.ShouldNotHavePublished<OrderCancelledEvent>();`

  • methodShouldNotHavePublished<TMessage>
    public static void ShouldNotHavePublished<TMessage>(this InMemoryOutboxStore store) where TMessage : notnull

    Asserts that no messages of type `TMessage` were stored.

    store: this InMemoryOutboxStore
    The in-memory outbox store.

    Type parameters: TMessage: The type of the message to assert on. Exceptions: InvalidOperationException: Thrown when any message of the type was found

  • methodShouldNotHavePublished<TMessage>
    public static void ShouldNotHavePublished<TMessage>(this InMemoryOutboxStore store, Func<TMessage, bool> predicate) where TMessage : notnull

    Asserts that no messages of type `TMessage` matching the given predicate were stored.

    store: this InMemoryOutboxStore
    The in-memory outbox store.
    predicate: Func<TMessage, bool>
    A predicate to filter matching messages.

    Type parameters: TMessage: The type of the message to assert on.

  • methodTotalPublishedCount
    public static int TotalPublishedCount(this InMemoryOutboxStore store)

    Returns the total number of stored messages across all types. Useful for asserting that an operation produced a specific number of side effects.

    store: this InMemoryOutboxStore
    The in-memory outbox store.

    Retorna: The total count of published messages.

Buscar en el Ecosistema EricksonLopez.*

Escribe el nombre de una librería, ID de paquete NuGet, tipo .NET o concepto arquitectónico para buscar en el portal.