Skip to content
Draft
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
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -154,3 +154,7 @@ The sample catalog data is defined in [catalog.json](https://github.com/dotnet/e
## eShop on Azure

For a version of this app configured for deployment on Azure, please view [the eShop on Azure](https://github.com/Azure-Samples/eShopOnAzure) repo.

## Item reservation review demo

A cross-service checkout example for reviewing agent-written code: [run the scenarios and inspect the architecture](docs/item-reservation/README.md). The [presenter guide](docs/item-reservation/presenter-guide.md) connects the same PR to four approaches to review.
95 changes: 95 additions & 0 deletions docs/item-reservation/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
# Item reservation: a system-level review example

**Feature:** reserve all the items in an order for ten minutes while payment is processed. Complete the reservation on timely payment. Release it on failure, cancellation, or expiry. If payment arrives after release, stop fulfillment and surface a payment review.

This is an agent-built feature spanning an existing shop, not a miniature code puzzle. The feature request sounds local; the implementation changes authority, event delivery, persistence, customer communication, and cancellation behavior. The payment processor remains a simulator. No real payment or refund is performed.

## Run the shop

Use the repository's .NET SDK and a running container runtime. From the repository root:

```sh
# Normal behavior: ten-minute reservation, five-second simulated payment.
aspire run

# Presenter timings: fifteen-second reservation, payment after twenty-five seconds.
ItemReservationDemo=late-payment aspire run

# Equivalent without the Aspire CLI:
ItemReservationDemo=late-payment dotnet run --project src/eShop.AppHost
```

Stop the AppHost before switching scenarios. Use a fresh local demo environment, or let previous orders finish first. The feature changes the payment protocol; it does not migrate already in-flight orders from the old availability-check workflow.

| Scenario | Reservation | Payment | Expected result |
| --- | --- | --- | --- |
| `completed` | 60 seconds | Success after 10 seconds | Items reserved → Paid |
| `failed` | 60 seconds | Failure after 10 seconds | Items reserved → Cancelled; quantities restored |
| `cancelled` | 60 seconds | Failure after 20 seconds | Click Cancel order while reserved; duplicate failure does not restore twice |
| `expired` | 15 seconds | Failure after 25 seconds | Expiry cancels the order before payment responds |
| `late-payment` | 15 seconds | Success after 25 seconds | Expiry cancels it, then Payment review needed; cannot ship |

These overrides also shorten the existing order grace-period scan to one second. The timer starts when Catalog successfully reserves the items, not when the user opens the checkout page. Configuration fails on an unknown scenario.

Sign in with the sample's seeded `alice` / `Pass123$` account, add a product, and place an order. The Orders page shows the reservation's UTC deadline and updates when outcomes arrive. Cancel order opens a confirmation form and sends a request; it does not promise that cancellation beat payment.

## The system path to show in CodeBoarding

Start with **WebApp → Ordering.API → Catalog.API → PaymentProcessor → Ordering.API → WebApp**. Then expand Catalog's `Reservations` folder and the shared event contracts. The services coordinate through RabbitMQ; these arrows are message flows, not new HTTP calls or shared database access.

```mermaid
flowchart LR
Customer[WebApp: checkout and order status] --> Ordering[Ordering: order lifecycle]
Ordering -->|Awaiting validation| Catalog[Catalog: ItemReservationService]
Catalog -->|ItemsReserved| Ordering
Ordering -->|Existing payment request event| Payment[PaymentProcessor: simulator]
Payment -->|Success or failure| Catalog
Ordering -->|Release requested| Catalog
Worker[ItemReservationWorker: expiry and replay] --> Catalog
Catalog -->|Atomic state and quantities| DB[(Catalog PostgreSQL)]
Catalog --> Outbox[Reservation outbox]
Outbox -->|Completed / Released / Rejected / Review required| Ordering
Ordering -->|Buyer-scoped update| Customer
```

The existing internal `StockConfirmed` order status and payment-request event retain their wire names. The customer UI calls this **Items reserved**, and new feature names use **item reservation**. This deliberately avoids a broad rename of unrelated historical contracts.

| Review stop | Entry point | Question |
| --- | --- | --- |
| Customer promise | `src/WebApp/Components/Pages/User/ItemReservationStatus.razor` | What does the customer believe has happened? |
| Allocation authority | `src/Catalog.API/Reservations/ItemReservationService.cs` | Who decides whether the last item belongs to this order? |
| Cancellation boundary | `src/Ordering.API/Application/Commands/CancelOrderCommandHandler.cs` | Is this a request or a completed fact? |
| Payment boundary | `src/Catalog.API/Reservations/ItemReservationEventHandlers.cs` | Does successful payment still imply a fulfillable order? |
| Recovery | `ReservationOutboxDispatcher`, `ItemReservationWorker`, `OrderingOutboxWorker` | What survives a crash between database commit and message publication? |
| Final ownership | `Order.SetItemReservationPaymentReviewRequired` | Who resolves a payment whose item reservation has ended? |

## Deterministic evidence

```sh
dotnet test --project tests/ItemReservation.FunctionalTests/ItemReservation.FunctionalTests.csproj
dotnet test --project tests/Ordering.UnitTests/Ordering.UnitTests.csproj
dotnet test --solution eShop.Web.slnf
```

The reservation tests start and remove a dedicated PostgreSQL container on a random loopback port. They apply the real migrations and use real transactions and row locks. Lifecycle tests advance a controllable clock, rather than sleeping ten minutes. They never reset the running shop's database.

Useful tests to run in front of the audience:

- `TwoCheckoutsForLastItem_OnlyOneSucceeds`: two concurrent commands, separate database contexts, one winner.
- `LatePaymentAfterItemsWereReallocated_DoesNotConsumeAnotherOrdersItems`: the first order's late payment cannot take the second order's item.
- `ExpiryAfterRestart_RestoresItemsFromPersistedReservation`: a new service instance recovers persisted reservations.
- `FailedPublication_IsRetriedFromDurableOutboxAfterRestart`: the state commits while publication fails, then a fresh dispatcher recovers it.
- `StaleCatalogEdit_CannotOverwriteAReservation`: an existing catalog update path also needs protection.

These database tests do not prove broker routing or browser behavior; those require the running application. A green suite is evidence about the exercised behaviors, not an architectural approval.

## Decisions made, and decisions left for humans

1. **Catalog owns reservation outcomes.** Ordering becomes Paid only after Catalog confirms completion. Available quantity falls at reservation time; payment does not decrement it again. Reservations are all-or-nothing across an order's item lines.
2. **One reservation per order.** Order IDs are the idempotency key. Terminal records prevent delayed requests from reviving cancelled orders. A changed basket needs a new order, not reuse of a reservation ID.
3. **The deadline is strict.** Payment received by Catalog at or after the deadline requires review, even if the expiry worker has not run yet. Workers may return quantities later than the exact deadline. Catalog host clocks must be synchronized across replicas.
4. **Cancellation is asynchronous.** Catalog serializes it with payment and expiry. Payment may win; a cancellation request is not a refund promise. Late successful payment becomes a visible, non-shippable review state. A real payment integration needs authorization/capture semantics, provider idempotency, reconciliation, and a refund/void workflow with an accountable owner.
5. **Delivery is at least once.** Database state and outgoing outcomes commit together. Publisher confirmations precede marking the outbox sent. Retries can duplicate messages; lifecycle operations are idempotent. The sample's failed-message acknowledgement is replaced with delayed requeue. Production needs bounded retries, dead-letter handling, backlog monitoring, and retention for the outbox and tombstones.
6. **Rollout is part of correctness.** Deploy the collaborating services together in this demo and drain legacy in-flight orders. A production rollout needs a versioned contract/compatibility plan, operational metrics, and a recovery procedure before it can ship.

The graph makes these boundaries easier to find. It does not decide the payment policy, prove every message ordering safe, or replace the engineer who accepts the trade-offs.
45 changes: 45 additions & 0 deletions docs/item-reservation/presenter-guide.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# Presenter guide: AI writes the code. Who assesses the risks?

Use the same feature throughout the lecture. Reveal the system gradually instead of asking the audience to read a large diff. The PR is the realistic review workload; the handful of opened functions are evidence for the discussion.

## Opening: one request, many consequences (5 minutes)

Show the original request:

> Reserve the items in an order for ten minutes while payment is processed. Release them if the order is cancelled or payment fails. Show the customer what happened.

Ask: “If an agent delivers this PR with green tests, what would you need to know before approving it?” Show the file count and the changed services. Do not use lines of code as a correctness metric. Generated migrations account for part of the diff and should be identified as such.

## 1. Shape the work before generation (10 minutes)

- **Plans and specifications:** write the deadline and all-or-nothing promise. Does the deadline mean payment started, provider succeeded, or Catalog received the result?
- **Repository context and constraints:** keep Catalog as the owner of quantities; tell the agent about existing payment events and integration logs.
- **Smaller changes and boundaries:** separate persistence, lifecycle, integration, and UI review, while retaining one end-to-end feature to assess.
- **Remaining judgment:** a well-followed plan can still encode the wrong business policy. Ask who chose ten minutes and who accepts the late-payment outcome.

## 2. Produce evidence about behavior (12 minutes)

- **Tests, types, and static checks:** show the concurrent last-item test and all-or-nothing basket test. An isolated happy-path test would miss the competition.
- **Independent reviewer agents:** ask for a payment/expiry counterexample, then verify its proposed path against the implementation. An agent's explanation is a hypothesis.
- **Runtime and failure testing:** demonstrate expiry followed by late payment. Point to the durable outbox recovery test.
- **Properties and state models:** state “a release restores each held unit at most once” and “a released reservation never becomes fulfillable.” Ask which event orderings the tests actually exercise.

## 3. Build enough understanding to review (13 minutes)

- **Explanations and navigable diffs:** summarize the changed promise, then open the small amount of code that establishes it.
- **System-level views:** open the new CodeBoarding PR review. Follow WebApp → Ordering → Catalog → PaymentProcessor; expand the reservation service and outbox. Show that the payment dependency changed even though checkout still looks familiar.
- **Interactive scenarios:** run `late-payment`. Predict the customer-facing states before watching them. Then trace why payment cannot consume another customer's reserved item.
- **Shared walkthroughs:** ask “What happens if Catalog commits and crashes before publishing?” Let the audience identify the missing component before expanding the worker and outbox.

## 4. Decide what may ship (8 minutes)

- **Blast radius and reversibility:** this touches fulfillment eligibility, quantities, and a shared message bus. Rolling back just the UI cannot restore the old protocol.
- **Evidence and accountable owners:** tests support invariants. An engineer still approves the deadline, payment compensation, and consistency model.
- **Release and recovery:** explain draining old orders, deploying matching event consumers, monitoring pending outcomes, and handling payment review.
- **Learning after delivery:** record unexpected event sequences and feed them into tests, constraints, and future review guidance.

## Close (2 minutes)

Return to the opening question. The useful result of review is that someone can explain the changed promises, the affected components, the evidence, and the remaining decisions. CodeBoarding is one aid in producing that understanding.

Total: approximately 50 minutes, including the short application and CodeBoarding demonstrations. Keep questions or a longer recovery demo as a ten-minute extension.
6 changes: 4 additions & 2 deletions eShop.Web.slnf
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,9 @@
"tests\\Ordering.FunctionalTests\\Ordering.FunctionalTests.csproj",
"tests\\Ordering.UnitTests\\Ordering.UnitTests.csproj",
"tests\\Webhooks.FunctionalTests\\Webhooks.FunctionalTests.csproj",
"tests\\eShop.AppHost.UnitTests\\eShop.AppHost.UnitTests.csproj"
"tests\\eShop.AppHost.UnitTests\\eShop.AppHost.UnitTests.csproj",
"src\\ItemReservation.Contracts\\ItemReservation.Contracts.csproj",
"tests\\ItemReservation.FunctionalTests\\ItemReservation.FunctionalTests.csproj"
]
}
}
}
4 changes: 3 additions & 1 deletion eShop.slnx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Solution>
<Solution>
<Folder Name="/src/">
<Project Path="src/eShop.AppHost/eShop.AppHost.csproj" />
<Project Path="src/Basket.API/Basket.API.csproj" />
Expand All @@ -8,6 +8,7 @@
<Project Path="src/EventBusRabbitMQ/EventBusRabbitMQ.csproj" />
<Project Path="src/Identity.API/Identity.API.csproj" />
<Project Path="src/IntegrationEventLogEF/IntegrationEventLogEF.csproj" />
<Project Path="src/ItemReservation.Contracts/ItemReservation.Contracts.csproj" />
<Project Path="src/Ordering.API/Ordering.API.csproj" />
<Project Path="src/OrderProcessor/OrderProcessor.csproj" />
<Project Path="src/Ordering.Domain/Ordering.Domain.csproj" />
Expand All @@ -25,6 +26,7 @@
<Project Path="tests/Basket.FunctionalTests/Basket.FunctionalTests.csproj" />
<Project Path="tests/Application.UnitTests/Application.UnitTests.csproj" />
<Project Path="tests/Catalog.FunctionalTests/Catalog.FunctionalTests.csproj" />
<Project Path="tests/ItemReservation.FunctionalTests/ItemReservation.FunctionalTests.csproj" />
<Project Path="tests/Ordering.FunctionalTests/Ordering.FunctionalTests.csproj" />
<Project Path="tests/Ordering.UnitTests/Ordering.UnitTests.csproj" />
<Project Path="tests/Webhooks.FunctionalTests/Webhooks.FunctionalTests.csproj" />
Expand Down
36 changes: 23 additions & 13 deletions src/Catalog.API/Apis/CatalogApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -387,22 +387,32 @@ public static async Task<Results<Created, BadRequest<ProblemDetails>, NotFound<P

catalogItem.Embedding = await services.CatalogAI.GetEmbeddingAsync(catalogItem);

var priceEntry = catalogEntry.Property(i => i.Price);

if (priceEntry.IsModified) // Save product's data and publish integration event through the Event Bus if price has changed
try
{
//Create Integration Event to be published through the Event Bus
var priceChangedEvent = new ProductPriceChangedIntegrationEvent(catalogItem.Id, productToUpdate.Price, priceEntry.OriginalValue);

// Achieving atomicity between original Catalog database operation and the IntegrationEventLog thanks to a local transaction
await services.EventService.SaveEventAndCatalogContextChangesAsync(priceChangedEvent);

// Publish through the Event Bus and mark the saved event as published
await services.EventService.PublishThroughEventBusAsync(priceChangedEvent);
var priceEntry = catalogEntry.Property(i => i.Price);

if (priceEntry.IsModified) // Save product's data and publish integration event through the Event Bus if price has changed
{
//Create Integration Event to be published through the Event Bus
var priceChangedEvent = new ProductPriceChangedIntegrationEvent(catalogItem.Id, productToUpdate.Price, priceEntry.OriginalValue);

// Achieving atomicity between original Catalog database operation and the IntegrationEventLog thanks to a local transaction
await services.EventService.SaveEventAndCatalogContextChangesAsync(priceChangedEvent);

// Publish through the Event Bus and mark the saved event as published
await services.EventService.PublishThroughEventBusAsync(priceChangedEvent);
}
else // Just save the updated product because the Product's Price hasn't changed.
{
await services.Context.SaveChangesAsync();
}
}
else // Just save the updated product because the Product's Price hasn't changed.
catch (DbUpdateConcurrencyException)
{
await services.Context.SaveChangesAsync();
return TypedResults.BadRequest<ProblemDetails>(new()
{
Detail = "Item availability changed during this update. Reload the item before retrying."
});
}
return TypedResults.Created($"/api/catalog/items/{id}");
}
Expand Down
5 changes: 4 additions & 1 deletion src/Catalog.API/Catalog.API.csproj
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
Expand Down Expand Up @@ -50,4 +50,7 @@
<InternalsVisibleTo Include="Catalog.FunctionalTests" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="../ItemReservation.Contracts/ItemReservation.Contracts.csproj" />
</ItemGroup>
</Project>
15 changes: 13 additions & 2 deletions src/Catalog.API/Extensions/Extensions.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using eShop.Catalog.API.Services;
using eShop.Catalog.API.Services;
using eShop.Catalog.API.Reservations;
using eShop.ItemReservation.Contracts;

public static class Extensions
{
Expand Down Expand Up @@ -30,7 +32,16 @@ public static void AddApplicationServices(this IHostApplicationBuilder builder)

builder.AddRabbitMqEventBus("eventbus")
.AddSubscription<OrderStatusChangedToAwaitingValidationIntegrationEvent, OrderStatusChangedToAwaitingValidationIntegrationEventHandler>()
.AddSubscription<OrderStatusChangedToPaidIntegrationEvent, OrderStatusChangedToPaidIntegrationEventHandler>();
.AddSubscription<OrderPaymentSucceededIntegrationEvent, CompleteItemReservationOnPaymentHandler>()
.AddSubscription<OrderPaymentFailedIntegrationEvent, ReleaseItemReservationOnPaymentFailureHandler>()
.AddSubscription<ItemReservationReleaseRequestedIntegrationEvent, ReleaseItemReservationOnCancellationHandler>();

builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddOptions<ItemReservationOptions>().BindConfiguration("ItemReservation")
.ValidateDataAnnotations().ValidateOnStart();
builder.Services.AddScoped<ItemReservationService>();
builder.Services.AddScoped<ReservationOutboxDispatcher>();
builder.Services.AddHostedService<ItemReservationWorker>();

builder.Services.AddOptions<CatalogOptions>()
.BindConfiguration(nameof(CatalogOptions));
Expand Down
Loading
Loading