# Lab 5: Run It Like Production

**30 minutes on the schedule, closer to 40 if you do every step** · Starts from `checkpoint-4` · Ends at `checkpoint-5` (the finished Roastery API)

Steps 1 and 2 need only the SDK, the Aspire templates, and the Aspire CLI. Step 3 needs Docker or Podman. Step 4 needs nothing extra.

!!! warning Short on time?
Do Steps 1 and 2 first; they are the point of the module. If the day is running long, cut in the same order as the [schedule](../schedule.md): skip **Step 4 (versioning)** first, then **Step 3 (container)**, which the instructor will demo. When you run out of time, `git checkout checkpoint-5` gets you the finished API with everything below already done.
!!!

## Step 1: Add the Aspire projects

Install the Aspire project templates once, if you did not already do it during [setup](../setup.md):

```bash
dotnet new install Aspire.ProjectTemplates
```

Then, from the `src` folder:

```bash
dotnet new aspire-apphost -n Roastery.AppHost
dotnet new aspire-servicedefaults -n Roastery.ServiceDefaults
dotnet sln add Roastery.AppHost Roastery.ServiceDefaults
cd Roastery.AppHost
dotnet add reference ../Roastery.Api ../Roastery.Payments
cd ../Roastery.Api
dotnet add reference ../Roastery.ServiceDefaults
cd ../Roastery.Payments
dotnet add reference ../Roastery.ServiceDefaults
```

Replace the AppHost's `AppHost.cs` with the version on the concepts page. Keep the `.WaitFor(payments)` line: it stops the API starting before the payment service is up. Keep the `.WithEnvironment("Payments__BaseUrl", …)` line too; the next part explains it.

!!! note
Building and running the AppHost requires the Aspire CLI (the dashboard and orchestrator bundle). If `dotnet run` on the AppHost complains it cannot resolve the Aspire bundle, install the CLI from [get.aspire.dev](https://get.aspire.dev) and re-run. The API, tests, and container build in the other steps do not need it.
!!!

**Wire up `ServiceDefaults`.** In both the API and the payments project, add `builder.AddServiceDefaults();` immediately after `CreateBuilder`, and `app.MapDefaultEndpoints();` near the other `Map` calls. Then, in the API's `Program.cs`:

- **Delete** the `builder.AddRoasteryTelemetry();` call. `ServiceDefaults` now configures OpenTelemetry, and calling both registers the instrumentation twice. You can also delete `Observability/Telemetry.cs`; if you do, delete the `using Roastery.Api.Observability;` line too. (The checkpoint leaves the file in place, unused.)
- **Delete** the two `MapHealthChecks` lines from Lab 4. `MapDefaultEndpoints()` maps `/health` and `/alive` for you.
- **Keep** the `AddDbContextCheck<RoasteryDbContext>()` registration. `ServiceDefaults` adds the endpoints and a `self` liveness check, not your database check.

**Point the payment client at the service name.** Change the fallback in the `PaymentClient` registration from `"https://localhost:7281"` to `"https+http://payments"`:

```csharp
builder.Services.AddHttpClient<PaymentClient>(client =>
        client.BaseAddress = new Uri(builder.Configuration["Payments:BaseUrl"] ?? "https+http://payments"));
```

This snippet already drops the `.AddStandardResilienceHandler()` call; the next paragraph explains why.

`payments` is the resource name from the AppHost. The `https+http://` scheme is service-discovery syntax for "use the HTTPS endpoint if the service has one, otherwise HTTP"; the resolver swaps in the real address that the AppHost injected as `services__payments__https__0`.

!!! warning Why the AppHost sets `Payments__BaseUrl`
The `??` only falls through when `Payments:BaseUrl` is not set, and `appsettings.json` still sets it to `https://localhost:7281` so the API keeps running on its own. Left alone, that value would win under Aspire too, and the API would call `localhost:7281` directly without ever using discovery. It would even appear to work, because Aspire happens to start payments on that port.

The AppHost's `.WithEnvironment("Payments__BaseUrl", "https+http://payments")` fixes that. Environment variables override `appsettings.json`, so under the AppHost the configured address becomes the service name and discovery resolves it. Run standalone, the API still uses `appsettings.json`; in a container, Step 3 sets the variable to a real URL.
!!!

**Remove the duplicate resilience handler.** The `ServiceDefaults` template calls `ConfigureHttpClientDefaults(http => http.AddStandardResilienceHandler())`, which gives *every* `HttpClient` a resilience pipeline. The `.AddStandardResilienceHandler()` from Lab 4 on `PaymentClient` adds a second pipeline inside the first. Now every retry from the outer pipeline runs the inner pipeline's retries too, and the timeouts nest. Delete the `.AddStandardResilienceHandler()` on the `PaymentClient` registration so only the default applies. The checkpoint does exactly that.

## Step 2: Run it and read the trace

Set `Roastery.AppHost` as the startup project and run it, or from the repo root:

```bash
dotnet run --project src/Roastery.AppHost
# or, with the Aspire CLI:
cd src/Roastery.AppHost && aspire run
```

The dashboard opens in the browser. If it does not, or it asks you to log in, copy the login URL from the console output (it looks like `https://localhost:17xxx/login?t=...`). The `?t=` token is what signs you in.

!!! note Files the Aspire CLI creates
`aspire run` may create `aspire.config.json` in the AppHost folder, which records which project is the AppHost. Commit it. It may also create a `.aspire/` folder holding a local bundle, which you should not commit; add `.aspire/` to `.gitignore` (the checkpoint already does this).
!!!

1. Confirm both `api` and `payments` show **Running**. Click each resource's endpoint and browse to `/health`; both should return `Healthy`.
2. Open `module-5.http`. Set `@baseUrl` to the `api` address shown in the dashboard (usually still `https://localhost:7181`). **Until you finish Step 4, the routes are not versioned yet**, so change `@api = {{baseUrl}}/api/v1` to `@api = {{baseUrl}}/api` for now, and skip the `v2` request at the bottom. Get a staff token and a customer token, then place an order as the customer.
3. Open **Traces** and find `POST /api/orders`. Expand it and find the outbound `HttpClient` call to `payments` and the `POST /charge` span from the payment service under it, which is the cross-service trace you came for. The fake provider fails about 30% of charges, so place a few more orders until you catch one where the `payments` call shows several attempts: that is the resilience handler retrying.
4. Advance the order to `Roasting`, then `Ready`, as staff. Open **Structured logs**, filter to `api`, and find the `OrderReadyNotifier` entry, `Order {OrderId} is ready; notifying {Email}`.

You will not see EF Core query spans in the trace. `ServiceDefaults` registers ASP.NET Core and `HttpClient` instrumentation only; EF Core instrumentation is a separate package (see the stretch goals).

## Step 3: Build and run the container

From the repo root:

```bash
dotnet publish src/Roastery.Api -c Release --os linux /t:PublishContainer -p:ContainerRepository=roastery-api
docker images roastery-api
```

Leaving out `--arch` builds for your machine's architecture, so on Apple Silicon you get an `arm64` image that runs natively. Add `--arch x64` only when the image is headed for an x64 host; forcing x64 on an ARM Mac runs it under emulation.

Run it with configuration supplied as environment variables. The container cannot reach the Aspire-hosted payments service by name, so point it at the host instead. Start the standalone payments service in another terminal first (`dotnet run --project src/Roastery.Payments --launch-profile https`):

```bash
docker run --rm -p 8080:8080 \
  -e ASPNETCORE_ENVIRONMENT=Development \
  -e ConnectionStrings__Roastery="Data Source=/tmp/roastery.db" \
  -e Jwt__SigningKey="roastery-dev-signing-key-change-me-32-bytes" \
  -e Payments__BaseUrl="https://host.docker.internal:7281" \
  roastery-api
```

Why each variable is there:

- `ASPNETCORE_ENVIRONMENT=Development`: the database migration and seed only run in Development, and `MapDefaultEndpoints()` only maps `/health` and `/alive` in Development. Without it you get an empty database with no tables, and the health endpoints return 404.
- `ConnectionStrings__Roastery`: the image runs as the non-root `app` user, which cannot write to the app folder, so the default `Data Source=roastery.db` fails. `/tmp` is writable. The database disappears with the container, which is fine for this step.
- `Payments__BaseUrl`: the same `Payments:BaseUrl` key the code reads, with `__` standing in for `:`.

!!! warning Linux hosts
`host.docker.internal` resolves automatically on Docker Desktop (macOS, Windows). On Linux, add `--add-host=host.docker.internal:host-gateway` to the `docker run` command.
!!!

Browse to `http://localhost:8080/api/v1/products`, or `http://localhost:8080/api/products` if you skipped Step 4. It is the same code, the same configuration keys, and a different environment.

**Only the menu is expected to work.** Placing an order calls payments over HTTPS on the host, and the development certificate is issued for `localhost`, not `host.docker.internal`, and is not trusted inside the container anyway. The charge fails with a TLS error. Making that work means a real certificate or running both services in containers, which is what Aspire and `azd` do for you.

!!! tip
`docker inspect roastery-api --format '{{.Config.User}} {{.Config.ExposedPorts}}'` shows the user the SDK chose and the exposed port: `1654 map[8080/tcp:{}]`. `1654` is the UID of the non-root `app` user built into the .NET images. Neither required a line of Dockerfile.
!!!

## Step 4: Version the API

```bash
cd src/Roastery.Api && dotnet add package Asp.Versioning.Http
```

Add the `AddApiVersioning` registration and the version set from the concepts page (`using Asp.Versioning;` at the top of `Program.cs`). Then move the endpoints under the versioned group. That takes two changes, or every URL ends up as `/api/v1/api/products`:

1. **Shorten the group prefixes.** In `ProductEndpoints.cs`, change `app.MapGroup("/api/products")` to `app.MapGroup("/products")`. In `OrderEndpoints.cs`, change `app.MapGroup("/api/orders")` to `app.MapGroup("/orders")`.
2. **Map them under `v1`.** In `Program.cs`, replace the `app.MapProductEndpoints();` and `app.MapOrderEndpoints();` calls with the `v1` group from the concepts page.

Leave the `/api/auth` group alone; token endpoints are not versioned.

Now add one `v2` endpoint: `GET /api/v2/products/{id}` returns the v1 product fields plus an `Origin` string. Create `Endpoints/ProductEndpointsV2.cs`:

==- ProductEndpointsV2.cs
```csharp
using Microsoft.AspNetCore.Http.HttpResults;
using Roastery.Api.Contracts;
using Roastery.Api.Services;

namespace Roastery.Api.Endpoints;

public record ProductDtoV2(int Id, string Name, string Roast, decimal Price, bool InStock, string Origin);

public static class ProductEndpointsV2
{
    public static IEndpointRouteBuilder MapProductEndpointsV2(this IEndpointRouteBuilder app)
    {
        app.MapGroup("/products").WithTags("Products")
           .MapGet("/{id:int}", GetProductV2).WithName("GetProductV2");
        return app;
    }

    static async Task<Results<Ok<ProductDtoV2>, NotFound>> GetProductV2(
        int id, IProductCatalog catalog, CancellationToken ct)
    {
        var product = await catalog.FindAsync(id, ct);
        if (product is null) return TypedResults.NotFound();

        var dto = product.ToDto();
        // v2 adds a (placeholder) Origin field; the roast name derives a plausible origin.
        var origin = product.Name.Split(' ').FirstOrDefault() ?? "Unknown";
        return TypedResults.Ok(new ProductDtoV2(dto.Id, dto.Name, dto.Roast, dto.Price, dto.InStock, origin));
    }
}
```
===

Map it in `Program.cs` right after the `v1` group, using the same version set:

```csharp
// v2 adds an Origin field to a single product endpoint to demonstrate side-by-side versions.
app.MapGroup("/api/v{version:apiVersion}").WithApiVersionSet(versions).MapToApiVersion(2)
   .MapProductEndpointsV2();
```

In `module-5.http`, set `@api` back to `{{baseUrl}}/api/v1`. Then check:

- `GET {{api}}/products` returns `200` with an `api-supported-versions: 1, 2` response header.
- `GET {{baseUrl}}/api/v2/products/1` returns the product with an `origin` field (`"Ethiopia"` for product 1).
- `GET {{api}}/products/1` returns the same product without `origin`.
- The old `GET /api/products` now returns `404`.

Scalar still shows a single OpenAPI document; there is one `AddOpenApi()` call, so both versions' routes appear in it as `/api/v{version}/...`. Separate per-version documents are a stretch goal.

**Fix the tests.** The integration tests still call the unversioned URLs. In `Roastery.Tests/OrderApiTests.cs`, change the four request paths to `/api/v1/products`, `/api/v1/orders/1/status` (twice), and `/api/v1/orders/2/status`, then run `dotnet test`.

## Stretch goals

- **Prove discovery is doing the work.** Change `Payments:BaseUrl` in the API's `appsettings.json` to a port nothing listens on, such as `https://localhost:7999`, then run under the AppHost. Orders still charge, because the AppHost's value replaces it. Run the API standalone and the same orders fail.
- **See EF Core in the trace.** Add the `OpenTelemetry.Instrumentation.EntityFrameworkCore` package to the API (it is prerelease, so `dotnet add package OpenTelemetry.Instrumentation.EntityFrameworkCore --prerelease`) and register it with `builder.Services.AddOpenTelemetry().WithTracing(t => t.AddEntityFrameworkCoreInstrumentation());`. Your queries then show up as spans under each request.
- **Link the notifier to the request.** The `OrderReadyNotifier` log entry has its own trace, not the `PUT`'s, because nothing carries the trace context through the `Channel`. Add an `ActivityContext` to `OrderReadyMessage`, capture `Activity.Current?.Context` when you write the message, and in the notifier start an `Activity` with it as the parent from an `ActivitySource` named `Roastery.Api` (the name `ServiceDefaults` already listens to).
- Replace SQLite with Postgres: `builder.AddPostgres("db").AddDatabase("roastery")` in the AppHost, `.WithReference(db)` on the API, the `Npgsql` EF Core provider, and a fresh migration. Note how little of the API changed.
- Deploy: `azd init` in the `src` folder, choose the AppHost, then `azd up`. Requires an Azure subscription and about ten minutes.
- Add the Aspire Redis resource and switch `HybridCache` to use it as the L2 with `AddRedisDistributedCache("cache")`.

## Common pitfalls

- **`dotnet new aspire-apphost` says no templates match.** Run `dotnet new install Aspire.ProjectTemplates` first.
- **Health endpoints 404 under Aspire.** `MapDefaultEndpoints()` is missing. If `/health` returns but reports nothing about the database, you deleted the `AddDbContextCheck` registration along with the old `MapHealthChecks` lines.
- **`payments` does not resolve.** `AddServiceDefaults()` is not called in the API (it registers service discovery), or `WithReference(payments)` is missing in the AppHost. If orders charge under Aspire only while `appsettings.json` has the right port, the `.WithEnvironment("Payments__BaseUrl", …)` line is missing and `appsettings.json` is winning (discovery resolves to the same `localhost:7281`, so the trace alone will not tell you).
- **Far more retry spans than expected.** Both `ServiceDefaults` and your `PaymentClient` registration add a standard resilience handler. Remove the per-client one.
- **Container exits on start, or every request fails.** Read `docker logs`. `SQLite Error 14: unable to open database file` means the connection string points somewhere the `app` user cannot write; use `/tmp`. `no such table` means `ASPNETCORE_ENVIRONMENT=Development` is missing, so migrations did not run.
- **`/health` returns 404 in the container.** Same cause: `MapDefaultEndpoints()` only maps health endpoints in Development.
- **Every URL is `/api/v1/api/products`.** You moved the groups under the versioned group without shortening `MapGroup("/api/products")` and `MapGroup("/api/orders")`.
- **Versioned routes 404.** The route template must be `/api/v{version:apiVersion}` exactly, and the group needs `WithApiVersionSet`.

## Checkpoint

```bash
git add -A && git commit -m "Lab 5 complete"
# or: git checkout checkpoint-5
```

That is the finished Roastery API. Head to the [Wrap-up](../wrap-up/review.md).
