Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions dictionary.txt
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,7 @@ OPTOUT
overfetching
OWIN
pageable
parameterless
Partitioner
pipefail
PKCE
Expand Down
1 change: 1 addition & 0 deletions src/Mocha/src/Demo/Demo.Billing/Demo.Billing.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
<PropertyGroup>
<AssemblyName>HotChocolate.Demo.Billing</AssemblyName>
<RootNamespace>HotChocolate.Demo.Billing</RootNamespace>
<TargetFramework>net10.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Demo.ServiceDefaults\Demo.ServiceDefaults.csproj" />
Expand Down
84 changes: 41 additions & 43 deletions src/Mocha/src/Demo/Demo.Billing/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
using Microsoft.EntityFrameworkCore;
using Mocha;
using Mocha.EntityFrameworkCore;
using Mocha.Mediator;
using Mocha.Inbox;
using Mocha.Mediator;
using Mocha.Outbox;
using Mocha.Transport.RabbitMQ;

Expand All @@ -15,24 +15,22 @@
builder.AddServiceDefaults();

// Database
builder.AddNpgsqlDbContext<BillingDbContext>("billing-db");
builder.AddNpgsqlDbContext<BillingDbContext>("billing-db", x => x.DisableTracing = true);

// RabbitMQ
builder.AddRabbitMQClient("rabbitmq", x => x.DisableTracing = true);

// Mocha.Mediator
builder.Services.AddMediator()
.AddBilling()
.AddInstrumentation()
.UseEntityFrameworkTransactions<BillingDbContext>();

// MessageBus
builder
.Services.AddMessageBus()
.AddInstrumentation()
// Event handlers
.AddEventHandler<OrderPlacedEventHandler>()
.AddEventHandler<ShipmentShippedEventHandler>()
// Batch event handlers
.AddBilling()
.AddBatchHandler<OrderPlacedBatchHandler>(opts =>
{
opts.MaxBatchSize = 5;
Expand All @@ -43,9 +41,6 @@
opts.MaxBatchSize = 500;
opts.BatchTimeout = TimeSpan.FromSeconds(5);
})
// Request handlers for saga commands
.AddRequestHandler<ProcessRefundCommandHandler>()
.AddRequestHandler<ProcessPartialRefundCommandHandler>()
.AddEntityFramework<BillingDbContext>(p =>
{
p.UsePostgresOutbox();
Expand All @@ -69,52 +64,55 @@
app.MapGet("/", () => "Billing Service");

// Invoices
app.MapGet("/api/invoices", async (ISender sender) =>
await sender.QueryAsync(new GetInvoicesQuery()));
app.MapGet("/api/invoices", async (ISender sender) => await sender.QueryAsync(new GetInvoicesQuery()));

app.MapGet("/api/invoices/{id:guid}", async (Guid id, ISender sender) =>
await sender.QueryAsync(new GetInvoiceByIdQuery(id)) is { } invoice
? Results.Ok(invoice)
: Results.NotFound());
app.MapGet(
"/api/invoices/{id:guid}",
async (Guid id, ISender sender) =>
await sender.QueryAsync(new GetInvoiceByIdQuery(id)) is { } invoice ? Results.Ok(invoice) : Results.NotFound());

app.MapGet("/api/invoices/order/{orderId:guid}", async (Guid orderId, ISender sender) =>
await sender.QueryAsync(new GetInvoiceByOrderIdQuery(orderId)) is { } invoice
? Results.Ok(invoice)
: Results.NotFound());
app.MapGet(
"/api/invoices/order/{orderId:guid}",
async (Guid orderId, ISender sender) =>
await sender.QueryAsync(new GetInvoiceByOrderIdQuery(orderId)) is { } invoice
? Results.Ok(invoice)
: Results.NotFound());

// Payments
app.MapPost("/api/payments/{invoiceId:guid}", async (Guid invoiceId, ProcessPaymentRequest request, ISender sender) =>
{
var result = await sender.SendAsync(new ProcessPaymentCommand(invoiceId, request.PaymentMethod));

if (!result.Success)
app.MapPost(
"/api/payments/{invoiceId:guid}",
async (Guid invoiceId, ProcessPaymentRequest request, ISender sender) =>
{
return result.Error == "Invoice not found"
? Results.NotFound(result.Error)
: Results.BadRequest(result.Error);
}
var result = await sender.SendAsync(new ProcessPaymentCommand(invoiceId, request.PaymentMethod));

return Results.Ok(result.Payment);
});
if (!result.Success)
{
return result.Error == "Invoice not found"
? Results.NotFound(result.Error)
: Results.BadRequest(result.Error);
}

app.MapGet("/api/payments", async (ISender sender) =>
await sender.QueryAsync(new GetPaymentsQuery()));
return Results.Ok(result.Payment);
});

app.MapGet("/api/payments", async (ISender sender) => await sender.QueryAsync(new GetPaymentsQuery()));

// Refunds
app.MapGet("/api/refunds", async (ISender sender) =>
await sender.QueryAsync(new GetRefundsQuery()));
app.MapGet("/api/refunds", async (ISender sender) => await sender.QueryAsync(new GetRefundsQuery()));

app.MapGet("/api/refunds/order/{orderId:guid}", async (Guid orderId, ISender sender) =>
await sender.QueryAsync(new GetRefundsByOrderIdQuery(orderId)));
app.MapGet(
"/api/refunds/order/{orderId:guid}",
async (Guid orderId, ISender sender) => await sender.QueryAsync(new GetRefundsByOrderIdQuery(orderId)));

// Revenue Summaries
app.MapGet("/api/revenue-summaries", async (ISender sender) =>
await sender.QueryAsync(new GetRevenueSummariesQuery()));

app.MapGet("/api/revenue-summaries/latest", async (ISender sender) =>
await sender.QueryAsync(new GetLatestRevenueSummaryQuery()) is { } summary
? Results.Ok(summary)
: Results.NotFound());
app.MapGet("/api/revenue-summaries", async (ISender sender) => await sender.QueryAsync(new GetRevenueSummariesQuery()));

app.MapGet(
"/api/revenue-summaries/latest",
async (ISender sender) =>
await sender.QueryAsync(new GetLatestRevenueSummaryQuery()) is { } summary
? Results.Ok(summary)
: Results.NotFound());

app.Run();

Expand Down
79 changes: 34 additions & 45 deletions src/Mocha/src/Demo/Demo.Catalog/Commands/PlaceOrderCommand.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using Demo.Catalog.Data;
using Demo.Catalog.Entities;
using Demo.Contracts.Events;
using Microsoft.EntityFrameworkCore;
using Mocha;
using Mocha.Mediator;

Expand All @@ -21,57 +20,47 @@ public class PlaceOrderCommandHandler(CatalogDbContext db, IMessageBus messageBu
public async ValueTask<PlaceOrderResult> HandleAsync(
PlaceOrderCommand command, CancellationToken cancellationToken)
{
var executionStrategy = db.Database.CreateExecutionStrategy();
var product = await db.Products.FindAsync(command.ProductId);
if (product is null)
{
return new PlaceOrderResult(false, Error: "Product not found");
}

return await executionStrategy.ExecuteAsync(async () =>
if (product.StockQuantity < command.Quantity)
{
await using var transaction = await db.Database.BeginTransactionAsync();
return new PlaceOrderResult(false, Error: "Insufficient stock");
}

var product = await db.Products.FindAsync(command.ProductId);
if (product is null)
{
return new PlaceOrderResult(false, Error: "Product not found");
}
var order = new OrderRecord
{
Id = Guid.NewGuid(),
ProductId = product.Id,
Quantity = command.Quantity,
CustomerId = command.CustomerId,
ShippingAddress = command.ShippingAddress,
TotalAmount = product.Price * command.Quantity,
Status = OrderStatus.Pending,
CreatedAt = DateTimeOffset.UtcNow,
UpdatedAt = DateTimeOffset.UtcNow
};

if (product.StockQuantity < command.Quantity)
{
return new PlaceOrderResult(false, Error: "Insufficient stock");
}
db.Orders.Add(order);

var order = new OrderRecord
await messageBus.PublishAsync(
new OrderPlacedEvent
{
Id = Guid.NewGuid(),
OrderId = order.Id,
ProductId = product.Id,
Quantity = command.Quantity,
CustomerId = command.CustomerId,
ShippingAddress = command.ShippingAddress,
TotalAmount = product.Price * command.Quantity,
Status = OrderStatus.Pending,
CreatedAt = DateTimeOffset.UtcNow,
UpdatedAt = DateTimeOffset.UtcNow
};

db.Orders.Add(order);
await db.SaveChangesAsync();

await messageBus.PublishAsync(
new OrderPlacedEvent
{
OrderId = order.Id,
ProductId = product.Id,
ProductName = product.Name,
Quantity = order.Quantity,
UnitPrice = product.Price,
TotalAmount = order.TotalAmount,
CustomerId = order.CustomerId,
ShippingAddress = order.ShippingAddress,
CreatedAt = order.CreatedAt
},
CancellationToken.None);

await transaction.CommitAsync();
ProductName = product.Name,
Quantity = order.Quantity,
UnitPrice = product.Price,
TotalAmount = order.TotalAmount,
CustomerId = order.CustomerId,
ShippingAddress = order.ShippingAddress,
CreatedAt = order.CreatedAt
},
CancellationToken.None);

return new PlaceOrderResult(true, order);
});
return new PlaceOrderResult(true, order);
}
}
1 change: 1 addition & 0 deletions src/Mocha/src/Demo/Demo.Catalog/Demo.Catalog.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
<PropertyGroup>
<AssemblyName>HotChocolate.Demo.Catalog</AssemblyName>
<RootNamespace>HotChocolate.Demo.Catalog</RootNamespace>
<TargetFramework>net10.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\Mocha.Transport.InMemory\Mocha.Transport.InMemory.csproj" />
Expand Down
17 changes: 3 additions & 14 deletions src/Mocha/src/Demo/Demo.Catalog/Program.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
using Demo.Catalog.Commands;
using Demo.Catalog.Data;
using Demo.Catalog.Handlers;
using Demo.Catalog.Queries;
using Demo.Catalog.Sagas;
using Microsoft.EntityFrameworkCore;
using Mocha;
using Mocha.EntityFrameworkCore;
Expand All @@ -18,31 +16,22 @@
builder.AddServiceDefaults();

// Database
builder.AddNpgsqlDbContext<CatalogDbContext>("catalog-db");
builder.AddNpgsqlDbContext<CatalogDbContext>("catalog-db", x => x.DisableTracing = true);

// RabbitMQ
builder.AddRabbitMQClient("rabbitmq", x => x.DisableTracing = true);

// Mocha.Mediator
builder.Services.AddMediator()
.AddCatalog()
.AddInstrumentation()
.UseEntityFrameworkTransactions<CatalogDbContext>();

// MessageBus
builder
.Services.AddMessageBus()
.AddInstrumentation()
// Event handlers
.AddEventHandler<PaymentCompletedEventHandler>()
.AddEventHandler<ShipmentCreatedEventHandler>()
// Request handlers
.AddRequestHandler<GetProductRequestHandler>()
.AddRequestHandler<ReserveInventoryCommandHandler>()
.AddRequestHandler<InspectReturnCommandHandler>()
.AddRequestHandler<RestockInventoryCommandHandler>()
// Sagas
.AddSaga<QuickRefundSaga>()
.AddSaga<ReturnProcessingSaga>()
.AddCatalog()
.AddEntityFramework<CatalogDbContext>(p =>
{
p.AddPostgresSagas();
Expand Down
1 change: 1 addition & 0 deletions src/Mocha/src/Demo/Demo.ServiceDefaults/Extensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ public static TBuilder ConfigureOpenTelemetry<TBuilder>(this TBuilder builder)
tracing
.AddSource(builder.Environment.ApplicationName)
.AddSource("Mocha")
.AddSource("Mocha.*")
.AddAspNetCoreInstrumentation(tracing =>
// Exclude health check requests from tracing
tracing.Filter = context =>
Expand Down
1 change: 1 addition & 0 deletions src/Mocha/src/Demo/Demo.Shipping/Demo.Shipping.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
<PropertyGroup>
<AssemblyName>HotChocolate.Demo.Shipping</AssemblyName>
<RootNamespace>HotChocolate.Demo.Shipping</RootNamespace>
<TargetFramework>net10.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Demo.ServiceDefaults\Demo.ServiceDefaults.csproj" />
Expand Down
10 changes: 3 additions & 7 deletions src/Mocha/src/Demo/Demo.Shipping/Program.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using Demo.Shipping.Commands;
using Demo.Shipping.Data;
using Demo.Shipping.Handlers;
using Demo.Shipping.Queries;
using Mocha;
using Mocha.EntityFrameworkCore;
Expand All @@ -14,25 +13,22 @@
builder.AddServiceDefaults();

// Database
builder.AddNpgsqlDbContext<ShippingDbContext>("shipping-db");
builder.AddNpgsqlDbContext<ShippingDbContext>("shipping-db", x => x.DisableTracing = true);

// RabbitMQ
builder.AddRabbitMQClient("rabbitmq", x => x.DisableTracing = true);

// Mocha.Mediator
builder.Services.AddMediator()
.AddShipping()
.AddInstrumentation()
.UseEntityFrameworkTransactions<ShippingDbContext>();

// MessageBus
builder
.Services.AddMessageBus()
.AddInstrumentation()
// Event handlers
.AddEventHandler<PaymentCompletedEventHandler>()
// Request handlers
.AddRequestHandler<GetShipmentStatusRequestHandler>()
.AddRequestHandler<CreateReturnLabelCommandHandler>()
.AddShipping()
.AddEntityFramework<ShippingDbContext>(p =>
{
p.UsePostgresOutbox();
Expand Down
22 changes: 22 additions & 0 deletions src/Mocha/src/Demo/Demo.slnx
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<Solution>
<Project Path="../Mocha.Abstractions/Mocha.Abstractions.csproj" />
<Project Path="../Mocha.Analyzers/Mocha.Analyzers.csproj" />
<Project Path="../Mocha.EntityFrameworkCore.Postgres/Mocha.EntityFrameworkCore.Postgres.csproj" />
<Project Path="../Mocha.EntityFrameworkCore/Mocha.EntityFrameworkCore.csproj" />
<Project Path="../Mocha.Hosting/Mocha.Hosting.csproj" />
<Project Path="../Mocha.Inbox/Mocha.Inbox.csproj" />
<Project Path="../Mocha.Mediator.Abstractions/Mocha.Mediator.Abstractions.csproj" />
<Project Path="../Mocha.Mediator/Mocha.Mediator.csproj" />
<Project Path="../Mocha.Outbox/Mocha.Outbox.csproj" />
<Project Path="../Mocha.Threading/Mocha.Threading.csproj" />
<Project Path="../Mocha.Transport.InMemory/Mocha.Transport.InMemory.csproj" />
<Project Path="../Mocha.Transport.RabbitMQ/Mocha.Transport.RabbitMQ.csproj" />
<Project Path="../Mocha.Utilities/Mocha.Utilities.csproj" />
<Project Path="../Mocha/Mocha.csproj" />
<Project Path="Demo.AppHost/Demo.AppHost.csproj" />
<Project Path="Demo.Billing/Demo.Billing.csproj" />
<Project Path="Demo.Catalog/Demo.Catalog.csproj" />
<Project Path="Demo.Contracts/Demo.Contracts.csproj" />
<Project Path="Demo.ServiceDefaults/Demo.ServiceDefaults.csproj" />
<Project Path="Demo.Shipping/Demo.Shipping.csproj" />
</Solution>
Loading
Loading