Skip to content

Latest commit

 

History

History
752 lines (577 loc) · 35 KB

README.md

File metadata and controls

752 lines (577 loc) · 35 KB

Encina.Messaging

NuGet License: MIT

Provider-agnostic abstractions for distributed messaging patterns in Encina.

This package provides interfaces and base implementations for common distributed system patterns, allowing you to choose your preferred persistence provider (Entity Framework Core, Dapper, ADO.NET, etc.) while maintaining consistency across your application.

Philosophy

🎯 All Patterns Are OPTIONAL

Encina.Messaging follows a pay-for-what-you-use philosophy. If your application is a simple CRUD app, you might only use transactions. If you're building a complex distributed system, you can enable all patterns.

// Simple app - only transactions
services.AddEncinaMessaging(config =>
{
    config.UseTransactions = true;
});

// Distributed system - all patterns
services.AddEncinaMessaging(config =>
{
    config.UseTransactions = true;
    config.UseOutbox = true;
    config.UseInbox = true;
    config.UseSagas = true;
    config.UseScheduling = true;
    config.UseRecoverability = true;
});

🔌 Provider Agnostic

Choose your data access strategy without vendor lock-in:

Provider Package Use Case
Entity Framework Core Encina.EntityFrameworkCore Full ORM, change tracking, migrations
Dapper Encina.Dapper Lightweight, SQL control, performance
ADO.NET Encina.Data Maximum performance, full control
Custom Implement IOutboxStore, etc. NoSQL, message queues, etc.

♻️ Consistent Across Providers

The Outbox pattern works the same way whether you use EF Core, Dapper, or ADO.NET:

// Same code, different providers
services.AddEncinaOutbox<AppDbContext>();  // EF Core
services.AddEncinaOutbox(dapperConnection); // Dapper
services.AddEncinaOutbox(adoConnection);    // ADO.NET

Messaging Patterns

1. Outbox Pattern (Reliable Event Publishing)

Problem: Events published before database commit can be lost if the system crashes.

Solution: Store events in the database (same transaction), publish later by background processor.

Guarantees: At-least-once delivery, durability, ordering.

// Domain event
public record OrderCreatedEvent(Guid OrderId) : INotification;

// Command handler
public class CreateOrderHandler : ICommandHandler<CreateOrderCommand, Order>
{
    public async ValueTask<Either<EncinaError, Order>> Handle(...)
    {
        var order = new Order { Id = Guid.NewGuid(), ... };
        _dbContext.Orders.Add(order);

        // Add event - will be stored in outbox (same transaction)
        order.AddDomainEvent(new OrderCreatedEvent(order.Id));

        await _dbContext.SaveChangesAsync();

        return order;
        // Events published asynchronously by OutboxProcessor
    }
}

Transactional write (ADO.NET and Dapper providers). On Encina.ADO.* and Encina.Dapper.* (SQL Server, PostgreSQL, MySQL), the notifications of a request that implements IHasNotifications are written by TransactionalOutboxPipelineBehavior<,> inside the request's single database transaction, so the business change and the outbox rows commit or roll back together and a failed write or commit fails the request. The behavior depends on ITransactionLeaseSource (namespace Encina.Messaging.Transactions); the relational IDbTransactionAccessor extends it, and the transaction behavior, the unit of work and the four messaging stores share one transaction through it (first participant owns, others join, a joiner's rollback makes the owner's commit return transaction.rollback_only). EF Core and MongoDB still write after the pipeline until their own slices of #718. See How to write the outbox inside the request's transaction and ADR-037.

2. Inbox Pattern (Idempotent Message Processing)

Problem: Messages from queues/webhooks can arrive multiple times, causing duplicate processing.

Solution: Track processed messages by ID, return cached response for duplicates.

Guarantees: Exactly-once processing.

// Mark command as idempotent
public record ProcessPaymentCommand(decimal Amount, string PaymentId)
    : ICommand<Receipt>, IIdempotentRequest;

// If same PaymentId arrives twice, cached receipt is returned
var result1 = await Encina.Send(command); // Processes
var result2 = await Encina.Send(command); // Returns cached result

Automatic purge of processed messages

When UseInbox is true and InboxOptions.EnableAutomaticPurge is true (the default), a hosted service (MessagePurgeService, internal; there is nothing to register yourself) deletes processed inbox messages whose retention period has passed. With EnableAutomaticPurge = false nothing is registered or run. The purge runs on all 10 database providers, and only processed, expired rows are deleted; an unprocessed or dead-lettered row is never removed.

services.AddEncinaEntityFrameworkCore<AppDbContext>(config =>
{
    config.UseInbox = true;
    config.InboxOptions.MessageRetentionPeriod = TimeSpan.FromDays(14);
    config.InboxOptions.PurgeInterval = TimeSpan.FromHours(6);
    config.InboxOptions.PurgeBatchSize = 500;
    // To disable automatic purge:
    // config.InboxOptions.EnableAutomaticPurge = false;
});
Option Default Valid values
EnableAutomaticPurge true true or false
MessageRetentionPeriod 30 days greater than zero
PurgeInterval 24 hours greater than zero and at most uint.MaxValue - 1 milliseconds (about 49.7 days, the limit of Task.Delay)
PurgeBatchSize 100 1 or more, no upper limit (the stores split a batch that exceeds a database limit)

A value outside the valid range throws ArgumentOutOfRangeException when you set it, so a misconfiguration fails at configuration time.

  • Schedule: one cycle after a random start-up pause (1 ms to 30 s), then one every PurgeInterval.
  • Cycle: deletes expired processed messages through IInboxStore in batches of PurgeBatchSize until a batch comes back shorter than the batch size. If the store returns only ids that the cycle already tried to remove, the cycle ends with a warning (EventId 2112, no progress) and the next interval runs normally.
  • Scope: no distributed lock, because the deletes are bounded and idempotent, so several hosts may run the purge at the same time. There is no tenant filter: the purge covers the whole deployment. It does not depend on any processor being enabled.
  • Failures: a Left from the store or an exception fails that cycle only. It is logged by error code (EventId 2110) or by exception type (EventId 2111), never by message text, and counted in encina.messaging.purge.cycle_failures_total (dimensions pattern and error_code, which carries the exception type name for an exception) on the Encina meter. The next cycle still runs. Deleted rows are counted in encina.messaging.purge.messages_deleted_total (dimension pattern).
  • Log events (range 2100-2199, EventIdRanges.MessagingInbox): 2107 loop started, 2108 nothing to purge, 2109 messages purged in a cycle, 2110 cycle failed with an error code, 2111 cycle threw an exception, 2112 no progress.

Reference: Inbox Pattern.

3. Saga Pattern (Distributed Transactions)

Problem: Multi-step business processes spanning services/aggregates can fail mid-way.

Solution: Orchestrate steps with compensating actions to rollback on failure.

public class OrderProcessingSaga : Saga<OrderData>
{
    protected override void ConfigureSteps()
    {
        // Step 1: Reserve inventory
        AddStep(
            execute: async (data, ctx, ct) =>
            {
                var result = await _Encina.Send(new ReserveInventoryCommand(...), ct);
                return result.Match(
                    Right: reservation => { data.ReservationId = reservation.Id; return data; },
                    Left: error => error
                );
            },
            compensate: async (data, ctx, ct) =>
            {
                // Rollback: Cancel reservation
                if (data.ReservationId.HasValue)
                    await _Encina.Send(new CancelReservationCommand(data.ReservationId.Value), ct);
            }
        );

        // Step 2: Charge customer
        AddStep(...);

        // Step 3: Ship order
        AddStep(...);
    }
}

// If Step 2 or 3 fails, Step 1 compensation runs automatically

4. Scheduled Messages (Delayed Execution)

Problem: Need to execute commands in the future (reminders, timeouts, recurring tasks).

Solution: Persist messages with execution time, process by background scheduler.

public class OrderHandler : ICommandHandler<CreateOrderCommand, Order>
{
    private readonly IMessageScheduler _scheduler;

    public async ValueTask<Either<EncinaError, Order>> Handle(...)
    {
        var order = new Order { ... };

        // Cancel order if not paid within 30 minutes
        await _scheduler.ScheduleAsync(
            new CancelUnpaidOrderCommand(order.Id),
            delay: TimeSpan.FromMinutes(30),
            context,
            cancellationToken);

        // Send reminder 24 hours before delivery
        await _scheduler.ScheduleAsync(
            new SendDeliveryReminderCommand(order.Id),
            executeAt: order.DeliveryDate.AddHours(-24),
            context,
            cancellationToken);

        return order;
    }
}

5. Recoverability Pipeline (Transient Error Handling)

Problem: Transient errors (network timeouts, temporary unavailability) can cause message processing failures.

Solution: Two-phase retry strategy with intelligent error classification.

Guarantees: Automatic retries for transient errors, dead letter queue for permanent failures.

services.AddEncinaMessaging(config =>
{
    config.UseRecoverability = true;
    // RecoverabilityOptions is get-only on the configuration: assign its members
    var recoverability = config.RecoverabilityOptions;

    // Immediate retries (in-memory, fast)
    recoverability.ImmediateRetries = 3;
    recoverability.ImmediateRetryDelay = TimeSpan.FromMilliseconds(100);
    recoverability.UseExponentialBackoffForImmediateRetries = true;

    // Delayed retries (persistent, scheduled). Off by default; turning them on
    // requires an IDelayedRetryStore, an IDelayedRetryMessageFactory and IEncina (registered below)
    recoverability.EnableDelayedRetries = true;
    recoverability.DelayedRetries =
    [
        TimeSpan.FromSeconds(30),
        TimeSpan.FromMinutes(5),
        TimeSpan.FromMinutes(30),
        TimeSpan.FromHours(2)
    ];

    // Jitter to prevent thundering herd
    recoverability.UseJitter = true;
    recoverability.MaxJitterPercent = 20;

    // Dead letter queue callback
    recoverability.OnPermanentFailure = async (failedMessage, ct) =>
    {
        await _deadLetterQueue.SendAsync(failedMessage, ct);
        _logger.LogError("Message {Id} moved to DLQ after {Attempts} attempts",
            failedMessage.Id, failedMessage.TotalAttempts);
    };
});

// Required because EnableDelayedRetries is true: register IEncina, and the store and its message
// factory (before or after the call above, in any order). Your own implementations, or a database
// provider package; no provider store exists yet (#594).
services.AddEncina(typeof(Program).Assembly);
services.AddEncinaDelayedRetryStore<MyDelayedRetryStore, MyDelayedRetryMessageFactory>();

Delayed retries are off by default (RecoverabilityOptions.EnableDelayedRetries is false). With the default, a failing message gets the immediate retries and then goes to the dead letter queue, and no delayed retry store is needed:

services.AddEncinaMessaging(config =>
{
    config.UseRecoverability = true;
    config.RecoverabilityOptions.ImmediateRetries = 3;
    // EnableDelayedRetries stays false: immediate retries + dead letter only
});

Register Recoverability once

Recoverability is registered once per host (ADR-050). Each of these combinations fails by design, in either order:

  • AddEncinaRecoverability() (or AddEncinaRecoverability<TClassifier>()) together with UseRecoverability = true.
  • The same registration called twice.
  • Two provider registrations with UseRecoverability = true, for example AddEncinaEntityFrameworkCore and an ADO.NET or Dapper AddMessagingServices.
  • A RecoverabilityOptions instance registered with AddSingleton next to either path.

The registration call throws an InvalidOperationException that names the duplicate, the module, ADR-050 and the fix. A duplicate added directly to the service collection after every Encina call (a raw AddScoped(typeof(IPipelineBehavior<,>), typeof(RecoverabilityPipelineBehavior<,>)) or AddSingleton(RecoverabilityOptions)) fails the host start with a Critical log (EventId 5458). Without a generic host that start check never runs; the registration-time error still does. Only the open generic registration of the behavior is checked: a closed registration for one request type is not detected.

Configure the options with AddEncinaRecoverability(options => ...) or the config.RecoverabilityOptions members, and read them through IOptions<RecoverabilityOptions>. The one supported composition is an application services.Configure<RecoverabilityOptions>(...) made before UseRecoverability: UseRecoverability overwrites it as a whole, so it does not merge with the two paths above.

When EnableDelayedRetries is true, an IDelayedRetryStore, an IDelayedRetryMessageFactory and IEncina (registered with AddEncina()) must be registered, even if DelayedRetries is empty: the flag alone decides. Otherwise the application fails at startup with an InvalidOperationException that names what is missing, ADR-050 and the fix. Without a generic host the startup check never runs: a missing store or factory fails when the scheduler is resolved, while a missing IEncina is caught only by the startup check (neither the scheduler nor the behavior needs it), so each processor cycle fails and logs ProcessingError (EventId 2847) while the processor keeps running. The startup check is interim and moves into the requirements validator of #2382.

Error Classification:

IErrorClassifier, ErrorClassification (Unknown, Transient, Permanent) and DefaultErrorClassifier live in core, namespace Encina.Recoverability; the Polly retry behavior, this pipeline and the Hangfire and Quartz job adapters classify through the same contract. The delayed-retry processor does not classify again: it uses the classification this pipeline recorded in the re-dispatch marker. OutboxBatchProcessor does not classify: it only schedules the next attempt (see below). The DefaultErrorClassifier looks at five things, in this order:

  1. Declared transience — the transient metadata (OutboundErrorMetadataKeys.Transient) that an outbound producer such as Encina.Refit sets wins over inference: true is transient, false is permanent.
  2. Connection-pool exhaustion — anywhere in the exception chain, the SqlClient text "max pool size was reached", the Npgsql text "connection pool has been exhausted" or the MySqlConnector text "All pooled connections are in use" is transient (the MongoDB driver raises a TimeoutException, transient by type). The match is on the English driver messages, because the drivers localize them; register a custom IErrorClassifier for another culture.
  3. Exception type — the exception passed to Classify, then EncinaError.Exception (inner exceptions are followed).
  4. Explicit error codes — the error code is compared, exactly and case-insensitively, with two fixed lists. It is never matched by substring, so codes such as saga.not_found, marten.aggregate_not_found or saga.invalid_status, which can succeed on a later attempt, are not permanent because of their code.
  5. Message patterns — only when the error has no causing exception. A message built around an exception (for example the dispatcher's encina.notification.exception message, which names the handler type) is not used, so a handler called CacheInvalidationHandler does not make a failure permanent.
Classification Exception types Error codes Message patterns Behavior
Transient TimeoutException, TaskCanceledException, IOException, HttpRequestException (5xx, 408, 429, no status) encina.timeout, encina.ratelimit.exceeded "timeout", "unavailable", "connection", "network", "retry", "rate_limit", "throttle", "busy", "overload" Retry immediately, then schedule delayed retries
Permanent ArgumentException, InvalidOperationException, NotSupportedException, UnauthorizedAccessException, FormatException, HttpRequestException (other 4xx) missing or mismatched handler (encina.handler.missing, encina.request.handler_missing, encina.request.handler_type_mismatch, encina.notification.missing_handle), authorization (encina.authorization.*), validation (Encina.guard.validation_failed, Repository.ValidationFailed, processor.validation_failed, gdpr.compliance_validation_failed, aiact.compliance_validation_failed), consent (consent.missing, consent.expired, consent.withdrawn, consent.requires_reconsent, consent.version_mismatch), DSR (dsr.restriction_active, dsr.subject_id_missing, dsr.identity_not_verified) "validation", "not_found", "unauthorized", "forbidden", "invalid", "bad_request" Move directly to DLQ
Unknown Other exceptions Any other code No match, or the error has a causing exception Treated as transient

Custom Error Classifier:

public class MyErrorClassifier : IErrorClassifier
{
    public ErrorClassification Classify(EncinaError error, Exception? exception)
    {
        // Custom classification logic
        if (exception is MyCustomTransientException)
            return ErrorClassification.Transient;

        if (error.Message.Contains("rate limit"))
            return ErrorClassification.Transient;

        return ErrorClassification.Permanent;
    }
}

// Register custom classifier
config.RecoverabilityOptions.ErrorClassifier = new MyErrorClassifier();

RecoverabilityPipelineBehavior takes the classifier from RecoverabilityOptions.ErrorClassifier, else the IErrorClassifier registered in DI (an optional constructor parameter), else DefaultErrorClassifier. A custom RecoverabilityOptions.ErrorClassifier replaces any registered classifier.

Outbound errors, Retry-After and non-idempotent sends:

An error from an outbound call such as Encina.Refit carries metadata from OutboundErrorMetadataKeys (see the Encina.Refit README). The recoverability layers act on it:

  • http.retry_after — the remaining immediate retries stop and the first delayed retry is scheduled at exactly that delay instead of DelayedRetries[0]. DelayedRetryProcessor uses the header delay for the next attempt instead of DelayedRetries[n]; the attempt still counts against DelayedRetries.Length. With delayed retries disabled, the error reaches the caller with the metadata. OutboxBatchProcessor sets NextRetryAtUtc no earlier than now plus http.retry_after when that is later than its own backoff.
  • http.retry_after ceiling — a Retry-After at or below the ceiling is honoured as above: the next attempt waits at least the header, never less. A Retry-After strictly above the ceiling schedules nothing (with delayed retries enabled, for RecoverabilityPipelineBehavior): the message is dead-lettered through the permanent-failure path (the outbox exhausts it at once, whatever its retry count) with the error code recoverability.retry_after_exceeds_ceiling (RecoverabilityErrorCodes.RetryAfterExceedsCeiling). A warning is logged (EventId 5454 in RecoverabilityPipelineBehavior, 5455 in DelayedRetryProcessor, 5456 in the outbox processor) and encina.retry.skipped_total is counted with the reason retry_after_exceeds_ceiling. The log and the metric's error_code tag keep the original error code, never the error message. The dead letter can be requeued or replayed like any other.
  • outbound.ambiguous — an ambiguous failure of a non-idempotent send (it may already have been processed) is returned like a permanent one, on the dead-letter path, unless the request has an IdempotencyKey. The IdempotencyKey is the one of the request context (IRequestContext.IdempotencyKey): it is an opt-in, and the Refit client must send it to the provider for the provider to deduplicate.

The ceiling is a TimeSpan that must be greater than zero and defaults to 24 hours. RecoverabilityOptions.MaxRetryAfter governs RecoverabilityPipelineBehavior and DelayedRetryProcessor; OutboxOptions.MaxRetryAfter governs the outbox batch processor. A positive TimeSpan.MaxValue is the explicit "no ceiling".

config.RecoverabilityOptions.MaxRetryAfter = TimeSpan.FromHours(6);
config.OutboxOptions.MaxRetryAfter = TimeSpan.FromHours(6);

The in-process Polly path (RetryAttribute) is unchanged and has its own limit: it honours a Retry-After up to RetryAttribute.MaxDelayMs. A longer one is never shortened: the retry is skipped (encina.retry.skipped_total, reason retry_after_exceeds_max) and the error returns with http.retry_after for the layers above to apply the ceiling.

The Hangfire and Quartz job adapters only use the classification (permanent or transient); they do not apply the Retry-After or non-idempotent rules.

6. Transactions (Automatic Database Transactions)

Problem: Manual transaction management is verbose and error-prone.

Solution: Declarative transactions with automatic commit/rollback.

// Marker interface
public record CreateOrderCommand(...) : ICommand<Order>, ITransactionalCommand;

// Or attribute
[Transaction(IsolationLevel = IsolationLevel.ReadCommitted)]
public record UpdateInventoryCommand(...) : ICommand;

// Transaction automatically wraps handler:
// - Begins before handler
// - Commits if Right
// - Rolls back if Left or exception

7. Content-Based Router (Message Routing)

Problem: Different messages require different handlers based on message content.

Solution: Route messages to handlers based on content inspection using configurable routing rules.

// Define routing rules
var definition = ContentRouterBuilder.Create<Order, string>()
    .When("Premium", o => o.CustomerType == "Premium" && o.Total > 500)
        .WithPriority(1)
        .RouteTo(async (o, ct) => await ProcessPremiumOrder(o, ct))

    .When("HighValue", o => o.Total > 1000)
        .WithPriority(2)
        .RouteTo(o => Right<EncinaError, string>("HighValueHandler"))

    .When("International", o => o.IsInternational)
        .WithPriority(3)
        .RouteTo(o => Right<EncinaError, string>("InternationalHandler"))

    .Default(o => Right<EncinaError, string>("StandardHandler"))
    .Build();

// Route messages
var result = await router.RouteAsync(definition, order);
result.Match(
    Right: r => Console.WriteLine($"Routed to: {r.RouteResults[0].RouteName}"),
    Left: e => Console.WriteLine($"Error: {e.Message}")
);

Configuration Options:

services.AddEncinaMessaging(config =>
{
    config.UseContentRouter = true;
    config.ContentRouterOptions = new ContentRouterOptions
    {
        ThrowOnNoMatch = true,        // Return error when no route matches
        AllowMultipleMatches = false, // Execute all matching routes
        EvaluateInParallel = false,   // Parallel route execution
        MaxDegreeOfParallelism = 4    // Concurrency limit when parallel
    };
});

Features:

  • Priority-based Routing: Routes are evaluated in priority order (lower = higher priority)
  • Multiple Handlers: Execute multiple matching routes with AllowMultipleMatches = true
  • Parallel Execution: Process routes in parallel with EvaluateInParallel = true
  • Named Routes: Identify routes for logging and debugging
  • Route Metadata: Attach custom metadata to routes
  • Execution Metrics: Track route execution time and matched route count

8. Dead Letter Queue (Messages That Failed for Good)

Problem: A message that exhausted its retries must not be lost, and an operator needs to inspect, replay or delete it.

Solution: Keep it in a persistent queue. Enable it with UseDeadLetterQueue on the configuration of a provider package (ADO.NET, Dapper, EF Core or MongoDB); the provider registers its IDeadLetterStore, DeadLetterOrchestrator (capture), IDeadLetterManager (list, replay, count, statistics, delete, cleanup), the health check and the cleanup processor. The registration also adds DeadLetterSourceCapture, and the five IntegrateWith* flags of DeadLetterOptions (on by default) make recoverability, outbox, inbox, scheduling and sagas capture their terminal failures.

services.AddEncinaADO(connectionString, config =>
{
    config.UseDeadLetterQueue = true;
    config.DeadLetterOptions.RetentionPeriod = TimeSpan.FromDays(14);
});
DeadLetterOptions member Default Effect
RetentionPeriod 7 days Time until ExpiresAtUtc; null disables expiry
CleanupInterval 1 hour How often DeadLetterCleanupProcessor deletes expired messages
EnableAutomaticCleanup true Registers the cleanup processor (needs a RetentionPeriod)
ReplayClaimTimeout 5 minutes How long a replay claim excludes other replays of the same message
OnDeadLetter none Callback run once per newly captured source message

Capture is idempotent per (SourcePattern, SourceMessageId), the store returns the oldest messages first, and the manager defaults to the ambient tenant. Setup per provider, schema scripts and the replay flow: How to enable the persistent dead letter queue. Design reasons: ADR-046.

Scheduling vs Hangfire/Quartz.NET

Key Differences

Feature Encina.Scheduling Hangfire Quartz.NET
Focus Domain messages (commands/events) General-purpose jobs General-purpose jobs
Integration Native Encina pattern External library External library
Persistence Your database (EF/Dapper/ADO) Own schema Own schema
UI No (use your own tools) Dashboard included No (3rd party)
Cron Jobs Yes Yes Yes
Delayed Messages Yes (primary use case) Yes Yes
Distributed Via database Via database/Redis Via database

When to Use What?

Use Encina.Scheduling when:

  • Scheduling domain commands/events (cancel order, send reminder)
  • Want consistent messaging patterns (outbox, inbox, scheduling)
  • Already using Encina
  • Prefer your existing database over separate job schema

Use Hangfire/Quartz when:

  • Need job management UI
  • Scheduling non-domain tasks (report generation, cleanup)
  • Complex scheduling requirements (multiple calendars, holidays)
  • Want mature ecosystem with extensive plugins

Can You Use Both?

Absolutely! They're complementary:

// Encina.Scheduling for domain messages
await _scheduler.ScheduleAsync(
    new CancelOrderCommand(orderId),
    delay: TimeSpan.FromMinutes(30));

// Hangfire for infrastructure tasks
BackgroundJob.Schedule(
    () => CleanupTempFiles(),
    TimeSpan.FromHours(1));

Integration Adapters (Future)

We plan to provide adapters so you can use Hangfire/Quartz as the backend:

// Use Hangfire as scheduling backend
services.AddEncinaScheduling()
    .UseHangfire();

// Use Quartz as scheduling backend
services.AddEncinaScheduling()
    .UseQuartz();

// Same IMessageScheduler API, different implementation

Pattern Coherence Across Providers

All messaging patterns share the same interfaces regardless of provider:

Outbox Pattern

// Interface (same for all providers)
public interface IOutboxMessage
{
    Guid Id { get; set; }
    string NotificationType { get; set; }
    string Content { get; set; }
    DateTime CreatedAtUtc { get; set; }
    DateTime? ProcessedAtUtc { get; set; }
    // ... consistent across providers
}

public interface IOutboxStore
{
    Task AddAsync(IOutboxMessage message, CancellationToken ct);
    Task<IEnumerable<IOutboxMessage>> GetPendingMessagesAsync(int batchSize, int maxRetries, CancellationToken ct);
    Task MarkAsProcessedAsync(Guid messageId, CancellationToken ct);
    Task MarkAsFailedAsync(Guid messageId, string error, DateTime? nextRetryAt, CancellationToken ct);
}

// Entity Framework Core implementation
public class OutboxMessageEF : IOutboxMessage
{
    // EF-specific: navigation properties, shadow properties, etc.
}

public class OutboxStoreEF : IOutboxStore
{
    private readonly DbContext _dbContext;

    public async Task AddAsync(IOutboxMessage message, CancellationToken ct)
    {
        _dbContext.Set<OutboxMessageEF>().Add((OutboxMessageEF)message);
        await _dbContext.SaveChangesAsync(ct);
    }
    // ... implements interface
}

// Dapper implementation
public class OutboxMessageDapper : IOutboxMessage
{
    // Dapper-specific: simple POCO, no navigation properties
}

public class OutboxStoreDapper : IOutboxStore
{
    private readonly IDbConnection _connection;

    public async Task AddAsync(IOutboxMessage message, CancellationToken ct)
    {
        await _connection.ExecuteAsync(
            "INSERT INTO OutboxMessages (...) VALUES (...)",
            message);
    }
    // ... implements interface
}

Benefits of This Approach

  1. Migration Path: Switch from EF Core to Dapper without changing domain code
  2. Testing: Mock IOutboxStore instead of DbContext
  3. Polyglot Persistence: Use EF Core for write model, Dapper for read model
  4. Learning: Understand patterns independent of ORM

Configuration Examples

Minimal (Transactions Only)

services.AddEncinaEntityFrameworkCore<AppDbContext>(config =>
{
    config.UseTransactions = true;
});

Standard (Transactions + Outbox)

services.AddEncinaEntityFrameworkCore<AppDbContext>(config =>
{
    config.UseTransactions = true;
    config.UseOutbox = true;
});

Advanced (All Patterns)

services.AddEncinaEntityFrameworkCore<AppDbContext>(config =>
{
    config.UseTransactions = true;
    config.UseOutbox = true;
    config.UseInbox = true;
    config.UseSagas = true;
    config.UseScheduling = true;
});

Fluent Builder (Alternative Syntax)

services.AddEncinaEntityFrameworkCore<AppDbContext>()
    .AddTransactions()
    .AddOutbox(options =>
    {
        options.BatchSize = 50;
        options.MaxRetries = 5;
    })
    .AddInbox(options =>
    {
        options.MessageRetentionPeriod = TimeSpan.FromDays(7);
    })
    .AddSagas()
    .AddScheduling();

Inspiration

This package draws inspiration from mature messaging frameworks:

  • Wolverine (ASP.NET): Outbox, Inbox, Sagas, Scheduled messages
  • MassTransit (.NET): Saga orchestration, message scheduling
  • NServiceBus (.NET): Outbox pattern, saga persistence
  • Axon Framework (Java): Event sourcing, sagas
  • Temporal (Polyglot): Workflow orchestration, durable execution

Health Checks

Encina.Messaging provides a unified health check abstraction for all providers. Health checks are automatically registered when you configure a provider.

Automatic Registration

// PostgreSQL Dapper - health check automatically registered
services.AddEncinaDapper<PostgreSqlConnection>(config =>
{
    config.UseOutbox = true;
    config.ProviderHealthCheck.Enabled = true; // Default
});

// The following health checks are registered:
// - "encina-postgresql" (database connectivity)
// - "encina-outbox" (outbox pattern health)

Configuration Options

services.AddEncinaDapper<PostgreSqlConnection>(config =>
{
    config.ProviderHealthCheck.Enabled = true;          // Enable/disable
    config.ProviderHealthCheck.Name = "my-custom-db";   // Custom name
    config.ProviderHealthCheck.Timeout = TimeSpan.FromSeconds(5);
    config.ProviderHealthCheck.Tags = ["critical", "database"];
});

Available Health Checks

Provider Default Name Tags
PostgreSQL encina-postgresql database, postgresql, ready
MySQL encina-mysql database, mysql, ready
SQL Server encina-sqlserver database, sqlserver, ready
MongoDB encina-mongodb database, mongodb, ready
RabbitMQ encina-rabbitmq messaging, rabbitmq, ready
Kafka encina-kafka messaging, kafka, ready
NATS encina-nats messaging, nats, ready
MQTT encina-mqtt messaging, mqtt, ready
Redis encina-redis caching, redis, ready
SignalR encina-signalr messaging, signalr, ready
gRPC encina-grpc messaging, grpc, ready

Custom Health Checks

Extend EncinaHealthCheck for custom implementations:

public sealed class MyCustomHealthCheck : EncinaHealthCheck
{
    public const string DefaultName = "my-custom-check";

    public MyCustomHealthCheck(IServiceProvider serviceProvider, ProviderHealthCheckOptions? options)
        : base(options?.Name ?? DefaultName, options?.Tags ?? ["encina", "custom", "ready"])
    {
        // Store dependencies
    }

    protected override Task<HealthCheckResult> CheckHealthCoreAsync(CancellationToken cancellationToken)
    {
        // Implement health logic
        return Task.FromResult(HealthCheckResult.Healthy("All good"));
    }
}

ASP.NET Core Integration

// In Program.cs
builder.Services.AddHealthChecks()
    .AddCheck<PostgreSqlHealthCheck>("database")
    .AddCheck<RabbitMQHealthCheck>("messaging");

// Map endpoints
app.MapHealthChecks("/health");
app.MapHealthChecks("/health/ready", new HealthCheckOptions
{
    Predicate = check => check.Tags.Contains("ready")
});

Roadmap

  • ✅ Core abstractions (IOutboxMessage, IInboxMessage, etc.)
  • ✅ Messaging configuration (opt-in patterns)
  • ✅ Health check abstractions and implementations
  • ✅ Recoverability Pipeline (two-phase retry, error classification, DLQ)
  • ✅ Content-Based Router (EIP pattern for message routing)
  • ⏳ Entity Framework Core provider
  • ⏳ Dapper provider
  • ⏳ ADO.NET provider
  • ⏳ Hangfire adapter
  • ⏳ Quartz.NET adapter
  • ⏳ Comprehensive tests
  • ⏳ Documentation and examples

License

This project is licensed under the MIT License - see the LICENSE file for details.