Reformat all code as per my preferred formatting.
This commit is contained in:
+10
-5
@@ -25,10 +25,15 @@ public class ApplyFeeHandlerTests
|
|||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
using var _ = new AssertionScope();
|
using var _ = new AssertionScope();
|
||||||
intents.CustomerWrite.Entity.Balance.Should().Be(account.Balance - command.Amount);
|
intents.CustomerWrite.Entity.Balance.Should()
|
||||||
intents.RevenueWrite.Entity.Balance.Should().Be(revenueAccount.Balance + command.Amount);
|
.Be(account.Balance - command.Amount);
|
||||||
intents.JournalWrite.Entity.Lines.Count.Should().BeGreaterThanOrEqualTo(2);
|
intents.RevenueWrite.Entity.Balance.Should()
|
||||||
intents.Event.AccountId.Should().Be(account.Id);
|
.Be(revenueAccount.Balance + command.Amount);
|
||||||
intents.Event.Amount.Should().Be(command.Amount);
|
intents.JournalWrite.Entity.Lines.Count.Should()
|
||||||
|
.BeGreaterThanOrEqualTo(2);
|
||||||
|
intents.Event.AccountId.Should()
|
||||||
|
.Be(account.Id);
|
||||||
|
intents.Event.Amount.Should()
|
||||||
|
.Be(command.Amount);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+12
-20
@@ -11,9 +11,7 @@ namespace FinancialApi.Application.Handlers;
|
|||||||
|
|
||||||
public static class ApplyFeeHandler
|
public static class ApplyFeeHandler
|
||||||
{
|
{
|
||||||
public static async Task<FeeContext> LoadAsync(
|
public static async Task<FeeContext> LoadAsync(ApplyFeeCommand cmd, IAccountQuery query, TimeProvider timeProvider)
|
||||||
ApplyFeeCommand cmd,
|
|
||||||
IAccountQuery query, TimeProvider timeProvider)
|
|
||||||
{
|
{
|
||||||
var source = await query.FindByIdAsync(cmd.AccountId);
|
var source = await query.FindByIdAsync(cmd.AccountId);
|
||||||
var dest = await query.FindByIdAsync(99999);
|
var dest = await query.FindByIdAsync(99999);
|
||||||
@@ -25,13 +23,8 @@ public static class ApplyFeeHandler
|
|||||||
return new FeeContext(source, dest, timeProvider.GetUtcNow());
|
return new FeeContext(source, dest, timeProvider.GetUtcNow());
|
||||||
}
|
}
|
||||||
|
|
||||||
public static (
|
public static ( IStorageAction<Account> CustomerWrite, IStorageAction<Account> RevenueWrite,
|
||||||
IStorageAction<Account> CustomerWrite,
|
IStorageAction<JournalEntry> JournalWrite, FeeAppliedEvent Event ) Handle(
|
||||||
IStorageAction<Account> RevenueWrite,
|
|
||||||
IStorageAction<JournalEntry> JournalWrite,
|
|
||||||
FeeAppliedEvent Event
|
|
||||||
)
|
|
||||||
Handle(
|
|
||||||
ApplyFeeCommand cmd,
|
ApplyFeeCommand cmd,
|
||||||
FeeContext context
|
FeeContext context
|
||||||
)
|
)
|
||||||
@@ -39,25 +32,24 @@ public static class ApplyFeeHandler
|
|||||||
var updatedSource = context.Source.ApplyPosting(cmd.Amount, EntryType.Debit);
|
var updatedSource = context.Source.ApplyPosting(cmd.Amount, EntryType.Debit);
|
||||||
var updatedRevenue = context.Destination.ApplyPosting(cmd.Amount, EntryType.Credit);
|
var updatedRevenue = context.Destination.ApplyPosting(cmd.Amount, EntryType.Credit);
|
||||||
var serviceFee = 0.5m;
|
var serviceFee = 0.5m;
|
||||||
|
|
||||||
var lines = new List<JournalLine>
|
var lines = new List<JournalLine>
|
||||||
{
|
{
|
||||||
new(updatedSource.Id, cmd.Amount, EntryType.Debit),
|
new(updatedSource.Id, cmd.Amount, EntryType.Debit),
|
||||||
new(updatedRevenue.Id, cmd.Amount - serviceFee, EntryType.Credit),
|
new(updatedRevenue.Id, cmd.Amount - serviceFee, EntryType.Credit),
|
||||||
new(updatedRevenue.Id, serviceFee, EntryType.Credit)
|
new(updatedRevenue.Id, serviceFee, EntryType.Credit)
|
||||||
};
|
};
|
||||||
|
|
||||||
var journalEntry = BalancedJournal.Create(Guid.NewGuid(),
|
var journalEntry = BalancedJournal.Create(
|
||||||
|
Guid.NewGuid(),
|
||||||
$"Service Fee Applied: {cmd.Amount} to Account {cmd.AccountId}",
|
$"Service Fee Applied: {cmd.Amount} to Account {cmd.AccountId}",
|
||||||
context.TimeStamp, lines);
|
context.TimeStamp,
|
||||||
|
lines
|
||||||
|
);
|
||||||
|
|
||||||
var @event = new FeeAppliedEvent(cmd.AccountId, cmd.Amount);
|
var @event = new FeeAppliedEvent(cmd.AccountId, cmd.Amount);
|
||||||
|
|
||||||
return (
|
return (Storage.Update(updatedSource), Storage.Update(updatedRevenue), Storage.Insert(journalEntry.Entry),
|
||||||
Storage.Update(updatedSource),
|
@event);
|
||||||
Storage.Update(updatedRevenue),
|
|
||||||
Storage.Insert(journalEntry.Entry),
|
|
||||||
@event
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+3
-12
@@ -5,20 +5,14 @@ namespace FinancialApi.Application.Handlers;
|
|||||||
|
|
||||||
public static class FinancialEventHandler
|
public static class FinancialEventHandler
|
||||||
{
|
{
|
||||||
public static void Handle(
|
public static void Handle(FeeAppliedEvent @event, IEventTracker store, ILogger logger)
|
||||||
FeeAppliedEvent @event,
|
|
||||||
IEventTracker store,
|
|
||||||
ILogger logger)
|
|
||||||
{
|
{
|
||||||
var message = $"FeeApplied: ${@event.Amount} moved from Account {@event.AccountId} to Account 99999.";
|
var message = $"FeeApplied: ${@event.Amount} moved from Account {@event.AccountId} to Account 99999.";
|
||||||
logger.LogInformation("BACKGROUND EVENT FIRED: {Message}", message);
|
logger.LogInformation("BACKGROUND EVENT FIRED: {Message}", message);
|
||||||
store.Add(message);
|
store.Add(message);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void Handle(
|
public static void Handle(FundsTransferredEvent @event, IEventTracker store, ILogger logger)
|
||||||
FundsTransferredEvent @event,
|
|
||||||
IEventTracker store,
|
|
||||||
ILogger logger)
|
|
||||||
{
|
{
|
||||||
var message =
|
var message =
|
||||||
$"FundsTransferred: ${@event.Amount} moved from Account {@event.SourceAccountId} to Account {@event.DestinationAccountId}.";
|
$"FundsTransferred: ${@event.Amount} moved from Account {@event.SourceAccountId} to Account {@event.DestinationAccountId}.";
|
||||||
@@ -26,10 +20,7 @@ public static class FinancialEventHandler
|
|||||||
store.Add(message);
|
store.Add(message);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void Handle(
|
public static void Handle(JournalReversedEvent @event, IEventTracker store, ILogger logger)
|
||||||
JournalReversedEvent @event,
|
|
||||||
IEventTracker store,
|
|
||||||
ILogger logger)
|
|
||||||
{
|
{
|
||||||
var message =
|
var message =
|
||||||
$"JournalReversed: Original Entry {@event.OriginalJournalId} was reversed by Entry {@event.ReversalJournalId}.";
|
$"JournalReversed: Original Entry {@event.OriginalJournalId} was reversed by Entry {@event.ReversalJournalId}.";
|
||||||
|
|||||||
+19
-18
@@ -11,38 +11,39 @@ namespace FinancialApi.Application.Handlers;
|
|||||||
|
|
||||||
public static class ReverseJournalHandler
|
public static class ReverseJournalHandler
|
||||||
{
|
{
|
||||||
public static async Task<JournalReversalContext?> LoadAsync(ReverseJournalCommand cmd, IReversalQuery query,
|
public static async Task<JournalReversalContext?> LoadAsync(
|
||||||
TimeProvider timeProvider)
|
ReverseJournalCommand cmd,
|
||||||
|
IReversalQuery query,
|
||||||
|
TimeProvider timeProvider
|
||||||
|
)
|
||||||
{
|
{
|
||||||
var data = await query.GetReversalDataAsync(cmd.OriginalJournalId);
|
var data = await query.GetReversalDataAsync(cmd.OriginalJournalId);
|
||||||
return data ?? throw new InvalidOperationException($"Journal Entry {cmd.OriginalJournalId} does not exist");
|
return data ?? throw new InvalidOperationException($"Journal Entry {cmd.OriginalJournalId} does not exist");
|
||||||
}
|
}
|
||||||
|
|
||||||
public static (
|
public static ( IStorageAction<JournalEntry> JournalWrite, UnitOfWork<Account> AccountWrites, JournalReversedEvent
|
||||||
IStorageAction<JournalEntry> JournalWrite,
|
Event) Handle(ReverseJournalCommand cmd, JournalReversalContext context)
|
||||||
UnitOfWork<Account> AccountWrites,
|
|
||||||
JournalReversedEvent Event)
|
|
||||||
Handle(ReverseJournalCommand cmd, JournalReversalContext context)
|
|
||||||
{
|
{
|
||||||
var reversalJournal =
|
var reversalJournal = BalancedJournal.CreateReversal(
|
||||||
BalancedJournal.CreateReversal(context.OriginalJournalEntry, $"Reversal: {cmd.Reason}", context.TimeStamp);
|
context.OriginalJournalEntry,
|
||||||
|
$"Reversal: {cmd.Reason}",
|
||||||
|
context.TimeStamp
|
||||||
|
);
|
||||||
var accountState = context.AffectedAccounts.ToDictionary(a => a.Id);
|
var accountState = context.AffectedAccounts.ToDictionary(a => a.Id);
|
||||||
|
|
||||||
reversalJournal.Entry.Lines.ForEach(l =>
|
reversalJournal.Entry.Lines.ForEach(l =>
|
||||||
{
|
{
|
||||||
var currentAccount = accountState[l.AccountId];
|
var currentAccount = accountState[l.AccountId];
|
||||||
accountState[l.AccountId] = currentAccount.ApplyPosting(l.Amount, l.Type);
|
accountState[l.AccountId] = currentAccount.ApplyPosting(l.Amount, l.Type);
|
||||||
});
|
}
|
||||||
|
);
|
||||||
var accountUow = new UnitOfWork<Account>();
|
var accountUow = new UnitOfWork<Account>();
|
||||||
foreach (var account in accountState.Values)
|
foreach (var account in accountState.Values)
|
||||||
{
|
{
|
||||||
accountUow.Update(account);
|
accountUow.Update(account);
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (Storage.Insert(reversalJournal.Entry), accountUow,
|
||||||
Storage.Insert(reversalJournal.Entry),
|
new JournalReversedEvent(cmd.OriginalJournalId, reversalJournal.Entry.Id));
|
||||||
accountUow,
|
|
||||||
new JournalReversedEvent(cmd.OriginalJournalId, reversalJournal.Entry.Id)
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+14
-18
@@ -11,8 +11,11 @@ namespace FinancialApi.Application.Handlers;
|
|||||||
|
|
||||||
public static class TransferFundsHandler
|
public static class TransferFundsHandler
|
||||||
{
|
{
|
||||||
public static async Task<TransferContext?> LoadAsync(TransferFundsCommand cmd, IAccountQuery query,
|
public static async Task<TransferContext?> LoadAsync(
|
||||||
TimeProvider timeProvider)
|
TransferFundsCommand cmd,
|
||||||
|
IAccountQuery query,
|
||||||
|
TimeProvider timeProvider
|
||||||
|
)
|
||||||
{
|
{
|
||||||
var source = await query.FindByIdAsync(cmd.SourceAccountId);
|
var source = await query.FindByIdAsync(cmd.SourceAccountId);
|
||||||
var dest = await query.FindByIdAsync(cmd.DestinationAccountId);
|
var dest = await query.FindByIdAsync(cmd.DestinationAccountId);
|
||||||
@@ -22,12 +25,8 @@ public static class TransferFundsHandler
|
|||||||
return new TransferContext(source, dest, timeProvider.GetUtcNow());
|
return new TransferContext(source, dest, timeProvider.GetUtcNow());
|
||||||
}
|
}
|
||||||
|
|
||||||
public static (
|
public static ( IStorageAction<Account> SourceWrite, IStorageAction<Account> DestWrite, IStorageAction<JournalEntry>
|
||||||
IStorageAction<Account> SourceWrite,
|
JournalWrite, FundsTransferredEvent Event ) Handle(TransferFundsCommand cmd, TransferContext context)
|
||||||
IStorageAction<Account> DestWrite,
|
|
||||||
IStorageAction<JournalEntry> JournalWrite,
|
|
||||||
FundsTransferredEvent Event
|
|
||||||
) Handle(TransferFundsCommand cmd, TransferContext context)
|
|
||||||
{
|
{
|
||||||
var updatedSource = context.Source.Debit(cmd.Amount);
|
var updatedSource = context.Source.Debit(cmd.Amount);
|
||||||
var updatedDest = context.Destination.Credit(cmd.Amount);
|
var updatedDest = context.Destination.Credit(cmd.Amount);
|
||||||
@@ -38,18 +37,15 @@ public static class TransferFundsHandler
|
|||||||
new(context.Destination.Id, cmd.Amount, EntryType.Credit)
|
new(context.Destination.Id, cmd.Amount, EntryType.Credit)
|
||||||
};
|
};
|
||||||
|
|
||||||
var journalEntry =
|
var journalEntry = BalancedJournal.Create(
|
||||||
BalancedJournal.Create(Guid.NewGuid(),
|
Guid.NewGuid(),
|
||||||
$"Transfer: {cmd.Amount} from {cmd.SourceAccountId} to {cmd.DestinationAccountId}",
|
$"Transfer: {cmd.Amount} from {cmd.SourceAccountId} to {cmd.DestinationAccountId}",
|
||||||
context.TimeStamp, lines);
|
context.TimeStamp,
|
||||||
|
lines
|
||||||
|
);
|
||||||
|
|
||||||
var @event = new FundsTransferredEvent(cmd.SourceAccountId, cmd.DestinationAccountId, cmd.Amount);
|
var @event = new FundsTransferredEvent(cmd.SourceAccountId, cmd.DestinationAccountId, cmd.Amount);
|
||||||
|
|
||||||
return (
|
return (Storage.Update(updatedSource), Storage.Update(updatedDest), Storage.Insert(journalEntry.Entry), @event);
|
||||||
Storage.Update(updatedSource),
|
|
||||||
Storage.Update(updatedDest),
|
|
||||||
Storage.Insert(journalEntry.Entry),
|
|
||||||
@event
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+2
-1
@@ -6,4 +6,5 @@ namespace FinancialApi.Application.Models;
|
|||||||
public record JournalReversalContext(
|
public record JournalReversalContext(
|
||||||
JournalEntry OriginalJournalEntry,
|
JournalEntry OriginalJournalEntry,
|
||||||
IReadOnlyList<Account> AffectedAccounts,
|
IReadOnlyList<Account> AffectedAccounts,
|
||||||
DateTimeOffset TimeStamp);
|
DateTimeOffset TimeStamp
|
||||||
|
);
|
||||||
@@ -10,8 +10,10 @@ public record BalancedJournal
|
|||||||
|
|
||||||
public static BalancedJournal Create(Guid id, string description, DateTimeOffset createdAt, List<JournalLine> lines)
|
public static BalancedJournal Create(Guid id, string description, DateTimeOffset createdAt, List<JournalLine> lines)
|
||||||
{
|
{
|
||||||
var debits = lines.Where(l => l.Type == EntryType.Debit).Sum(l => l.Amount);
|
var debits = lines.Where(l => l.Type == EntryType.Debit)
|
||||||
var credits = lines.Where(l => l.Type == EntryType.Credit).Sum(l => l.Amount);
|
.Sum(l => l.Amount);
|
||||||
|
var credits = lines.Where(l => l.Type == EntryType.Credit)
|
||||||
|
.Sum(l => l.Amount);
|
||||||
|
|
||||||
if (debits != credits)
|
if (debits != credits)
|
||||||
{
|
{
|
||||||
@@ -26,7 +28,8 @@ public record BalancedJournal
|
|||||||
public static BalancedJournal CreateReversal(JournalEntry original, string reason, DateTimeOffset now)
|
public static BalancedJournal CreateReversal(JournalEntry original, string reason, DateTimeOffset now)
|
||||||
{
|
{
|
||||||
var reversedLines = original.Lines.Select(l =>
|
var reversedLines = original.Lines.Select(l =>
|
||||||
l with { Type = l.Type == EntryType.Debit ? EntryType.Credit : EntryType.Debit })
|
l with { Type = l.Type == EntryType.Debit ? EntryType.Credit : EntryType.Debit }
|
||||||
|
)
|
||||||
.ToList();
|
.ToList();
|
||||||
|
|
||||||
return Create(Guid.NewGuid(), reason, now, reversedLines);
|
return Create(Guid.NewGuid(), reason, now, reversedLines);
|
||||||
|
|||||||
@@ -7,9 +7,7 @@ public record JournalEntry
|
|||||||
public DateTimeOffset CreatedAt { get; init; }
|
public DateTimeOffset CreatedAt { get; init; }
|
||||||
public List<JournalLine> Lines { get; init; } = [];
|
public List<JournalLine> Lines { get; init; } = [];
|
||||||
|
|
||||||
internal JournalEntry()
|
internal JournalEntry() { }
|
||||||
{
|
|
||||||
}
|
|
||||||
|
|
||||||
internal JournalEntry(Guid id, string description, DateTimeOffset createdAt, List<JournalLine> lines)
|
internal JournalEntry(Guid id, string description, DateTimeOffset createdAt, List<JournalLine> lines)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -14,22 +14,30 @@ public class AccountDbContext(DbContextOptions<AccountDbContext> options) : DbCo
|
|||||||
modelBuilder.Entity<Account>()
|
modelBuilder.Entity<Account>()
|
||||||
.HasKey(x => x.Id);
|
.HasKey(x => x.Id);
|
||||||
|
|
||||||
modelBuilder.Entity<Account>().HasData(
|
modelBuilder.Entity<Account>()
|
||||||
new Account(1, 10000000.00m, "Credit"),
|
.HasData(
|
||||||
new Account(2, 50000000.00m, "Liability"),
|
new Account(1, 10000000.00m, "Credit"),
|
||||||
new Account(99999, 0.00m, "Revenue")
|
new Account(2, 50000000.00m, "Liability"),
|
||||||
);
|
new Account(99999, 0.00m, "Revenue")
|
||||||
|
);
|
||||||
|
|
||||||
modelBuilder.Entity<JournalEntry>(builder =>
|
modelBuilder.Entity<JournalEntry>(builder =>
|
||||||
{
|
|
||||||
builder.HasKey(x => x.Id);
|
|
||||||
builder.OwnsMany(x => x.Lines, line =>
|
|
||||||
{
|
{
|
||||||
line.WithOwner().HasForeignKey("JournalEntryId");
|
builder.HasKey(x => x.Id);
|
||||||
line.Property<int>("Id").ValueGeneratedOnAdd();
|
builder.OwnsMany(
|
||||||
line.HasKey("Id");
|
x => x.Lines,
|
||||||
line.Property(x => x.Type).HasConversion<string>();
|
line =>
|
||||||
});
|
{
|
||||||
});
|
line.WithOwner()
|
||||||
|
.HasForeignKey("JournalEntryId");
|
||||||
|
line.Property<int>("Id")
|
||||||
|
.ValueGeneratedOnAdd();
|
||||||
|
line.HasKey("Id");
|
||||||
|
line.Property(x => x.Type)
|
||||||
|
.HasConversion<string>();
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -10,8 +10,7 @@ public class ReversalQuery(AccountDbContext db, TimeProvider timeProvider) : IRe
|
|||||||
{
|
{
|
||||||
public async Task<JournalReversalContext?> GetReversalDataAsync(Guid journalEntryId)
|
public async Task<JournalReversalContext?> GetReversalDataAsync(Guid journalEntryId)
|
||||||
{
|
{
|
||||||
var entry = await db.JournalEntries
|
var entry = await db.JournalEntries.Include(x => x.Lines)
|
||||||
.Include(x => x.Lines)
|
|
||||||
.AsNoTracking()
|
.AsNoTracking()
|
||||||
.FirstOrDefaultAsync(x => x.Id == journalEntryId);
|
.FirstOrDefaultAsync(x => x.Id == journalEntryId);
|
||||||
|
|
||||||
@@ -20,10 +19,11 @@ public class ReversalQuery(AccountDbContext db, TimeProvider timeProvider) : IRe
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
var accountIds = entry.Lines.Select(l => l.AccountId).Distinct().ToList();
|
var accountIds = entry.Lines.Select(l => l.AccountId)
|
||||||
|
.Distinct()
|
||||||
|
.ToList();
|
||||||
|
|
||||||
var accounts = await db.Accounts
|
var accounts = await db.Accounts.AsNoTracking()
|
||||||
.AsNoTracking()
|
|
||||||
.Where(a => accountIds.Contains(a.Id))
|
.Where(a => accountIds.Contains(a.Id))
|
||||||
.ToListAsync();
|
.ToListAsync();
|
||||||
|
|
||||||
|
|||||||
@@ -27,13 +27,14 @@ public static class Extensions
|
|||||||
builder.Services.AddServiceDiscovery();
|
builder.Services.AddServiceDiscovery();
|
||||||
|
|
||||||
builder.Services.ConfigureHttpClientDefaults(http =>
|
builder.Services.ConfigureHttpClientDefaults(http =>
|
||||||
{
|
{
|
||||||
// Turn on resilience by default
|
// Turn on resilience by default
|
||||||
http.AddStandardResilienceHandler();
|
http.AddStandardResilienceHandler();
|
||||||
|
|
||||||
// Turn on service discovery by default
|
// Turn on service discovery by default
|
||||||
http.AddServiceDiscovery();
|
http.AddServiceDiscovery();
|
||||||
});
|
}
|
||||||
|
);
|
||||||
|
|
||||||
// Uncomment the following to restrict the allowed schemes for service discovery.
|
// Uncomment the following to restrict the allowed schemes for service discovery.
|
||||||
// builder.Services.Configure<ServiceDiscoveryOptions>(options =>
|
// builder.Services.Configure<ServiceDiscoveryOptions>(options =>
|
||||||
@@ -48,31 +49,34 @@ public static class Extensions
|
|||||||
where TBuilder : IHostApplicationBuilder
|
where TBuilder : IHostApplicationBuilder
|
||||||
{
|
{
|
||||||
builder.Logging.AddOpenTelemetry(logging =>
|
builder.Logging.AddOpenTelemetry(logging =>
|
||||||
{
|
{
|
||||||
logging.IncludeFormattedMessage = true;
|
logging.IncludeFormattedMessage = true;
|
||||||
logging.IncludeScopes = true;
|
logging.IncludeScopes = true;
|
||||||
});
|
}
|
||||||
|
);
|
||||||
|
|
||||||
builder.Services.AddOpenTelemetry()
|
builder.Services.AddOpenTelemetry()
|
||||||
.WithMetrics(metrics =>
|
.WithMetrics(metrics =>
|
||||||
{
|
{
|
||||||
metrics.AddAspNetCoreInstrumentation()
|
metrics.AddAspNetCoreInstrumentation()
|
||||||
.AddHttpClientInstrumentation()
|
.AddHttpClientInstrumentation()
|
||||||
.AddRuntimeInstrumentation();
|
.AddRuntimeInstrumentation();
|
||||||
})
|
}
|
||||||
|
)
|
||||||
.WithTracing(tracing =>
|
.WithTracing(tracing =>
|
||||||
{
|
{
|
||||||
tracing.AddSource(builder.Environment.ApplicationName)
|
tracing.AddSource(builder.Environment.ApplicationName)
|
||||||
.AddAspNetCoreInstrumentation(tracing =>
|
.AddAspNetCoreInstrumentation(tracing =>
|
||||||
// Exclude health check requests from tracing
|
// Exclude health check requests from tracing
|
||||||
tracing.Filter = context =>
|
tracing.Filter = context =>
|
||||||
!context.Request.Path.StartsWithSegments(HealthEndpointPath)
|
!context.Request.Path.StartsWithSegments(HealthEndpointPath) &&
|
||||||
&& !context.Request.Path.StartsWithSegments(AlivenessEndpointPath)
|
!context.Request.Path.StartsWithSegments(AlivenessEndpointPath)
|
||||||
)
|
)
|
||||||
// Uncomment the following line to enable gRPC instrumentation (requires the OpenTelemetry.Instrumentation.GrpcNetClient package)
|
// Uncomment the following line to enable gRPC instrumentation (requires the OpenTelemetry.Instrumentation.GrpcNetClient package)
|
||||||
//.AddGrpcClientInstrumentation()
|
//.AddGrpcClientInstrumentation()
|
||||||
.AddHttpClientInstrumentation();
|
.AddHttpClientInstrumentation();
|
||||||
});
|
}
|
||||||
|
);
|
||||||
|
|
||||||
builder.AddOpenTelemetryExporters();
|
builder.AddOpenTelemetryExporters();
|
||||||
|
|
||||||
@@ -86,7 +90,8 @@ public static class Extensions
|
|||||||
|
|
||||||
if (useOtlpExporter)
|
if (useOtlpExporter)
|
||||||
{
|
{
|
||||||
builder.Services.AddOpenTelemetry().UseOtlpExporter();
|
builder.Services.AddOpenTelemetry()
|
||||||
|
.UseOtlpExporter();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Uncomment the following lines to enable the Azure Monitor exporter (requires the Azure.Monitor.OpenTelemetry.AspNetCore package)
|
// Uncomment the following lines to enable the Azure Monitor exporter (requires the Azure.Monitor.OpenTelemetry.AspNetCore package)
|
||||||
@@ -119,10 +124,10 @@ public static class Extensions
|
|||||||
app.MapHealthChecks(HealthEndpointPath);
|
app.MapHealthChecks(HealthEndpointPath);
|
||||||
|
|
||||||
// Only health checks tagged with the "live" tag must pass for app to be considered alive
|
// Only health checks tagged with the "live" tag must pass for app to be considered alive
|
||||||
app.MapHealthChecks(AlivenessEndpointPath, new HealthCheckOptions
|
app.MapHealthChecks(
|
||||||
{
|
AlivenessEndpointPath,
|
||||||
Predicate = r => r.Tags.Contains("live")
|
new HealthCheckOptions { Predicate = r => r.Tags.Contains("live") }
|
||||||
});
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return app;
|
return app;
|
||||||
|
|||||||
@@ -6,9 +6,10 @@ namespace FinancialApi;
|
|||||||
public class DomainExceptionHandler : IExceptionHandler
|
public class DomainExceptionHandler : IExceptionHandler
|
||||||
{
|
{
|
||||||
public async ValueTask<bool> TryHandleAsync(
|
public async ValueTask<bool> TryHandleAsync(
|
||||||
HttpContext httpContext,
|
HttpContext httpContext,
|
||||||
Exception exception,
|
Exception exception,
|
||||||
CancellationToken cancellationToken)
|
CancellationToken cancellationToken
|
||||||
|
)
|
||||||
{
|
{
|
||||||
if (exception is not (InvalidOperationException or ArgumentException))
|
if (exception is not (InvalidOperationException or ArgumentException))
|
||||||
{
|
{
|
||||||
@@ -25,8 +26,7 @@ public class DomainExceptionHandler : IExceptionHandler
|
|||||||
|
|
||||||
httpContext.Response.StatusCode = problemDetails.Status.Value;
|
httpContext.Response.StatusCode = problemDetails.Status.Value;
|
||||||
await httpContext.Response.WriteAsJsonAsync(problemDetails, cancellationToken);
|
await httpContext.Response.WriteAsJsonAsync(problemDetails, cancellationToken);
|
||||||
|
|
||||||
return true;
|
|
||||||
|
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -19,8 +19,7 @@ builder.Services.AddProblemDetails();
|
|||||||
|
|
||||||
var connectionString = "Data Source=demo.db";
|
var connectionString = "Data Source=demo.db";
|
||||||
|
|
||||||
builder.Services.AddDbContext<AccountDbContext>(options =>
|
builder.Services.AddDbContext<AccountDbContext>(options => options.UseSqlite(connectionString));
|
||||||
options.UseSqlite(connectionString));
|
|
||||||
|
|
||||||
builder.Services.AddScoped<IAccountQuery, AccountQuery>();
|
builder.Services.AddScoped<IAccountQuery, AccountQuery>();
|
||||||
builder.Services.AddScoped<IReversalQuery, ReversalQuery>();
|
builder.Services.AddScoped<IReversalQuery, ReversalQuery>();
|
||||||
@@ -33,13 +32,14 @@ builder.Services.AddOpenApi();
|
|||||||
builder.AddServiceDefaults();
|
builder.AddServiceDefaults();
|
||||||
|
|
||||||
builder.Host.UseWolverine(opts =>
|
builder.Host.UseWolverine(opts =>
|
||||||
{
|
{
|
||||||
opts.Discovery.IncludeAssembly(typeof(DemoEventStore).Assembly);
|
opts.Discovery.IncludeAssembly(typeof(DemoEventStore).Assembly);
|
||||||
opts.Discovery.IncludeAssembly(typeof(ApplyFeeHandler).Assembly);
|
opts.Discovery.IncludeAssembly(typeof(ApplyFeeHandler).Assembly);
|
||||||
opts.PersistMessagesWithSqlite(connectionString);
|
opts.PersistMessagesWithSqlite(connectionString);
|
||||||
opts.UseEntityFrameworkCoreTransactions();
|
opts.UseEntityFrameworkCoreTransactions();
|
||||||
opts.Policies.AutoApplyTransactions();
|
opts.Policies.AutoApplyTransactions();
|
||||||
});
|
}
|
||||||
|
);
|
||||||
builder.Host.UseResourceSetupOnStartup();
|
builder.Host.UseResourceSetupOnStartup();
|
||||||
|
|
||||||
var app = builder.Build();
|
var app = builder.Build();
|
||||||
@@ -60,32 +60,44 @@ if (app.Environment.IsDevelopment())
|
|||||||
|
|
||||||
app.UseHttpsRedirection();
|
app.UseHttpsRedirection();
|
||||||
|
|
||||||
app.MapPost("/accounts/apply-fee", async (ApplyFeeCommand cmd, IMessageBus bus) =>
|
app.MapPost(
|
||||||
{
|
"/accounts/apply-fee",
|
||||||
await bus.InvokeAsync(cmd);
|
async (ApplyFeeCommand cmd, IMessageBus bus) =>
|
||||||
return Results.Accepted();
|
|
||||||
});
|
|
||||||
|
|
||||||
app.MapPost("/accounts/transfer", async (TransferFundsCommand cmd, IMessageBus bus) =>
|
|
||||||
{
|
|
||||||
await bus.InvokeAsync(cmd);
|
|
||||||
return Results.Accepted();
|
|
||||||
});
|
|
||||||
|
|
||||||
app.MapPost("/journal/reverse", async (ReverseJournalCommand cmd, IMessageBus bus) =>
|
|
||||||
{
|
|
||||||
await bus.InvokeAsync(cmd);
|
|
||||||
return Results.Accepted();
|
|
||||||
});
|
|
||||||
|
|
||||||
app.MapGet("/events", (IEventTracker tracker) =>
|
|
||||||
{
|
|
||||||
if (tracker is DemoEventStore store)
|
|
||||||
{
|
{
|
||||||
return Results.Ok(store.CapturedEvents);
|
await bus.InvokeAsync(cmd);
|
||||||
|
return Results.Accepted();
|
||||||
}
|
}
|
||||||
|
);
|
||||||
|
|
||||||
return Results.NotFound();
|
app.MapPost(
|
||||||
});
|
"/accounts/transfer",
|
||||||
|
async (TransferFundsCommand cmd, IMessageBus bus) =>
|
||||||
|
{
|
||||||
|
await bus.InvokeAsync(cmd);
|
||||||
|
return Results.Accepted();
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
app.MapPost(
|
||||||
|
"/journal/reverse",
|
||||||
|
async (ReverseJournalCommand cmd, IMessageBus bus) =>
|
||||||
|
{
|
||||||
|
await bus.InvokeAsync(cmd);
|
||||||
|
return Results.Accepted();
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
app.MapGet(
|
||||||
|
"/events",
|
||||||
|
(IEventTracker tracker) =>
|
||||||
|
{
|
||||||
|
if (tracker is DemoEventStore store)
|
||||||
|
{
|
||||||
|
return Results.Ok(store.CapturedEvents);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Results.NotFound();
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
app.Run();
|
app.Run();
|
||||||
Reference in New Issue
Block a user