Skip to content

Latest commit

 

History

History
675 lines (520 loc) · 26.9 KB

README.md

File metadata and controls

675 lines (520 loc) · 26.9 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

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;
    config.RecoverabilityOptions = new RecoverabilityOptions
    {
        // Immediate retries (in-memory, fast)
        ImmediateRetries = 3,
        ImmediateRetryDelay = TimeSpan.FromMilliseconds(100),
        UseExponentialBackoffForImmediateRetries = true,

        // Delayed retries (persistent, scheduled)
        EnableDelayedRetries = true,
        DelayedRetries = [
            TimeSpan.FromSeconds(30),
            TimeSpan.FromMinutes(5),
            TimeSpan.FromMinutes(30),
            TimeSpan.FromHours(2)
        ],

        // Jitter to prevent thundering herd
        UseJitter = true,
        MaxJitterPercent = 20,

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

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.
  • 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 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.