hopefully not a horribly foolish refactoring
This commit is contained in:
parent
59d660165f
commit
1ecaf64dea
82 changed files with 782 additions and 398 deletions
|
@ -1,13 +0,0 @@
|
|||
using System.Data;
|
||||
using Microsoft.Data.SqlClient;
|
||||
using Npgsql;
|
||||
|
||||
namespace Femto.Modules.Blog.Infrastructure.DbConnection;
|
||||
|
||||
public class DbConnectionFactory(string connectionString) : IDbConnectionFactory
|
||||
{
|
||||
public IDbConnection GetConnection()
|
||||
{
|
||||
return new NpgsqlConnection(connectionString);
|
||||
}
|
||||
}
|
|
@ -1,9 +0,0 @@
|
|||
using System.Data;
|
||||
using Microsoft.Data.SqlClient;
|
||||
|
||||
namespace Femto.Modules.Blog.Infrastructure.DbConnection;
|
||||
|
||||
public interface IDbConnectionFactory
|
||||
{
|
||||
IDbConnection GetConnection();
|
||||
}
|
|
@ -1,78 +0,0 @@
|
|||
using System.Text.Json;
|
||||
using Femto.Modules.Blog.Data;
|
||||
using MediatR;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Quartz;
|
||||
|
||||
namespace Femto.Modules.Blog.Infrastructure.Integration.Outbox;
|
||||
|
||||
[DisallowConcurrentExecution]
|
||||
internal class MailmanJob(
|
||||
Outbox outbox,
|
||||
BlogContext context,
|
||||
ILogger<MailmanJob> logger,
|
||||
IMediator mediator
|
||||
) : IJob
|
||||
{
|
||||
public async Task Execute(IJobExecutionContext executionContext)
|
||||
{
|
||||
try
|
||||
{
|
||||
var messages = await outbox.GetPendingMessages(executionContext.CancellationToken);
|
||||
|
||||
logger.LogTrace("loaded {Count} outbox messages to process", messages.Count);
|
||||
foreach (var message in messages)
|
||||
{
|
||||
try
|
||||
{
|
||||
var notificationType = OutboxMessageTypeRegistry.GetType(message.EventType);
|
||||
|
||||
if (notificationType is null)
|
||||
{
|
||||
logger.LogWarning(
|
||||
"unmapped event type {Type}. skipping.",
|
||||
message.EventType
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
var notification =
|
||||
JsonSerializer.Deserialize(message.Payload, notificationType)
|
||||
as INotification;
|
||||
|
||||
if (notification is null)
|
||||
throw new Exception("notification is null");
|
||||
|
||||
logger.LogTrace(
|
||||
"publishing outbox message {EventType}. Id: {Id}, AggregateId: {AggregateId}",
|
||||
message.EventType,
|
||||
message.Id,
|
||||
message.AggregateId
|
||||
);
|
||||
|
||||
await mediator.Publish(notification, executionContext.CancellationToken);
|
||||
|
||||
message.Succeed();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.LogError(
|
||||
e,
|
||||
"Error processing event {EventId} for aggregate {AggregateId}",
|
||||
message.Id,
|
||||
message.AggregateId
|
||||
);
|
||||
|
||||
message.Fail(e.ToString());
|
||||
}
|
||||
|
||||
await context.SaveChangesAsync(executionContext.CancellationToken);
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.LogError(e, "Error while processing outbox");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,40 +0,0 @@
|
|||
using System.Reflection;
|
||||
using System.Text.Json;
|
||||
using Femto.Common.Attributes;
|
||||
using Femto.Common.Integration;
|
||||
using Femto.Modules.Blog.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Femto.Modules.Blog.Infrastructure.Integration.Outbox;
|
||||
|
||||
internal class Outbox(BlogContext context)
|
||||
{
|
||||
public async Task AddMessage<TMessage>(Guid aggregateId, TMessage message, CancellationToken cancellationToken)
|
||||
where TMessage : IIntegrationEvent
|
||||
{
|
||||
var eventType = typeof(TMessage).GetCustomAttribute<EventTypeAttribute>();
|
||||
if (eventType is null)
|
||||
throw new InvalidOperationException($"{typeof(TMessage).Name} does not have EventType attribute");
|
||||
|
||||
await context.Outbox.AddAsync(
|
||||
new(
|
||||
message.EventId,
|
||||
aggregateId,
|
||||
eventType.Name,
|
||||
JsonSerializer.Serialize(message)
|
||||
),
|
||||
cancellationToken
|
||||
);
|
||||
}
|
||||
|
||||
public async Task<IList<OutboxEntry>> GetPendingMessages(CancellationToken cancellationToken)
|
||||
{
|
||||
var now = DateTime.UtcNow;
|
||||
|
||||
return await context
|
||||
.Outbox.Where(message => message.Status == OutboxEntryStatus.Pending)
|
||||
.Where(message => message.NextRetryAt == null || message.NextRetryAt <= now)
|
||||
.OrderBy(message => message.CreatedAt)
|
||||
.ToListAsync(cancellationToken);
|
||||
}
|
||||
}
|
|
@ -1,59 +0,0 @@
|
|||
namespace Femto.Modules.Blog.Infrastructure.Integration.Outbox;
|
||||
|
||||
internal class OutboxEntry
|
||||
{
|
||||
private const int MaxRetries = 5;
|
||||
|
||||
public Guid Id { get; private set; }
|
||||
|
||||
public string EventType { get; private set; } = null!;
|
||||
public Guid AggregateId { get; private set; }
|
||||
|
||||
public string Payload { get; private set; } = null!;
|
||||
|
||||
public DateTime CreatedAt { get; private set; }
|
||||
|
||||
public DateTime? ProcessedAt { get; private set; }
|
||||
public DateTime? NextRetryAt { get; private set; }
|
||||
public int RetryCount { get; private set; } = 0;
|
||||
public string? LastError { get; private set; }
|
||||
public OutboxEntryStatus Status { get; private set; }
|
||||
|
||||
private OutboxEntry() { }
|
||||
|
||||
public OutboxEntry(Guid eventId, Guid aggregateId, string eventType, string payload)
|
||||
{
|
||||
this.Id = eventId;
|
||||
this.EventType = eventType;
|
||||
this.AggregateId = aggregateId;
|
||||
this.Payload = payload;
|
||||
this.CreatedAt = DateTime.UtcNow;
|
||||
}
|
||||
|
||||
public void Succeed()
|
||||
{
|
||||
this.ProcessedAt = DateTime.UtcNow;
|
||||
this.Status = OutboxEntryStatus.Completed;
|
||||
}
|
||||
|
||||
public void Fail(string error)
|
||||
{
|
||||
if (this.RetryCount >= MaxRetries)
|
||||
{
|
||||
this.Status = OutboxEntryStatus.Failed;
|
||||
}
|
||||
else
|
||||
{
|
||||
this.LastError = error;
|
||||
this.NextRetryAt = DateTime.UtcNow.AddSeconds(Math.Pow(2, this.RetryCount));
|
||||
this.RetryCount++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public enum OutboxEntryStatus
|
||||
{
|
||||
Pending,
|
||||
Completed,
|
||||
Failed
|
||||
}
|
|
@ -1,20 +0,0 @@
|
|||
using System.Collections.Concurrent;
|
||||
using System.Collections.Immutable;
|
||||
|
||||
namespace Femto.Modules.Blog.Infrastructure.Integration.Outbox;
|
||||
|
||||
internal static class OutboxMessageTypeRegistry
|
||||
{
|
||||
private static readonly ConcurrentDictionary<string, Type> Mapping = new();
|
||||
|
||||
public static void RegisterOutboxMessages(IImmutableDictionary<string, Type> mapping)
|
||||
{
|
||||
foreach (var (key, value) in mapping)
|
||||
{
|
||||
Mapping.TryAdd(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
public static Type? GetType(string eventName) => Mapping.GetValueOrDefault(eventName);
|
||||
|
||||
}
|
|
@ -1,58 +0,0 @@
|
|||
using Femto.Common.Domain;
|
||||
using Femto.Modules.Blog.Data;
|
||||
using MediatR;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Femto.Modules.Blog.Infrastructure.PipelineBehaviours;
|
||||
|
||||
internal class SaveChangesPipelineBehaviour<TRequest, TResponse>(
|
||||
BlogContext context,
|
||||
IPublisher publisher,
|
||||
ILogger<SaveChangesPipelineBehaviour<TRequest, TResponse>> logger
|
||||
) : IPipelineBehavior<TRequest, TResponse>
|
||||
where TRequest : notnull
|
||||
{
|
||||
public async Task<TResponse> Handle(
|
||||
TRequest request,
|
||||
RequestHandlerDelegate<TResponse> next,
|
||||
CancellationToken cancellationToken
|
||||
)
|
||||
{
|
||||
var response = await next(cancellationToken);
|
||||
|
||||
if (context.ChangeTracker.HasChanges())
|
||||
{
|
||||
|
||||
await EmitDomainEvents(cancellationToken);
|
||||
|
||||
logger.LogDebug("saving changes");
|
||||
await context.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
private async Task EmitDomainEvents(CancellationToken cancellationToken)
|
||||
{
|
||||
var domainEvents = context
|
||||
.ChangeTracker.Entries<Entity>()
|
||||
.SelectMany(e =>
|
||||
{
|
||||
var events = e.Entity.DomainEvents;
|
||||
e.Entity.ClearDomainEvents();
|
||||
return events;
|
||||
})
|
||||
.ToList();
|
||||
|
||||
logger.LogTrace("loaded {Count} domain events", domainEvents.Count);
|
||||
|
||||
foreach (var domainEvent in domainEvents)
|
||||
{
|
||||
logger.LogTrace(
|
||||
"publishing {Type} domain event {Id}",
|
||||
domainEvent.GetType().Name,
|
||||
domainEvent.EventId
|
||||
);
|
||||
await publisher.Publish(domainEvent, cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue