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
77 changes: 77 additions & 0 deletions .claude/plans/2026-11-15-issue-1484-add-aspire.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# Issue #1484 — Add .NET Aspire (AppHost + ServiceDefaults) to main

https://github.com/DevBetterCom/DevBetterWeb/issues/1484

Branch: `issue-1484-add-aspire`

## Assumptions

- Latest Aspire = 13.6.5 (Aspire.AppHost.Sdk / Aspire.Hosting.*); ServiceDefaults packages at
Microsoft.Extensions.* 11.0.0 and OpenTelemetry 1.21.0. All projects target net11.0.
- docker-compose only models SQL Server, so SQL Server is the only AppHost dependency.
Azure Storage (Azurite) and email are not in docker-compose and stay out of scope.
- The existing `/health` endpoint must keep working in every environment (used in prod), so
ServiceDefaults maps `/health` and `/alive` unconditionally instead of Development-only.
- The standard resilience handler must not break Vimeo uploads (60 min client timeouts) or
duplicate non-idempotent POSTs: retries disabled for unsafe methods, and the Vimeo clients
opt out of the default resilience pipeline.
- Serilog owns logging; logs are forwarded to OpenTelemetry providers only when an OTLP
endpoint is configured (i.e. under Aspire), so production logging is unchanged.
- OpenTelemetry metrics/tracing are only registered when an OTLP endpoint is configured, because
Application Insights 3.x is built on OpenTelemetry and would otherwise pick them up in prod.
- Pre-existing bug found during the smoke run: Mediator 3 registers handlers as singletons by
default, so Development DI validation failed (singleton DomainEventHandler<T> consuming scoped
IHandle<T>). Fixed by setting Mediator's ServiceLifetime to Scoped.
- Local migrations currently only run in Development inside a container. The AppHost sets
`ApplyLocalMigrations=true` so the Development web project migrates the fresh Aspire DB.

## Phase 1 — ServiceDefaults project
- [x] Add `src/DevBetterWeb.ServiceDefaults` (net11, IsAspireSharedProject) with `Extensions.cs`
- [x] Central package versions for ServiceDiscovery, Http.Resilience, OpenTelemetry.*

## Phase 2 — AppHost project
- [x] Add `src/DevBetterWeb.AppHost` (Aspire.AppHost.Sdk 13.6.5, net11)
- [x] Model SQL Server (persistent data volume) + `DevBetterWeb` database, referenced by web
as `DefaultConnection`; web waits for the database
- [x] Pass `ApplyLocalMigrations=true` to web
- [x] Add both projects to `DevBetterWeb.slnx`

## Phase 3 — Wire Web
- [x] Reference ServiceDefaults; call `AddServiceDefaults()` / `MapDefaultEndpoints()`
- [x] Replace ad-hoc `AddHealthChecks` / `MapHealthChecks("/health")`
- [x] Serilog `writeToProviders` when OTLP endpoint configured
- [x] Honor `ApplyLocalMigrations` config flag
- [x] Vimeo HttpClients remove default resilience handlers

## Phase 4 — Tests
- [x] New `tests/DevBetterWeb.AppHost.Tests` using Aspire.Hosting.Testing: build the app model
(no containers started) and assert sql/db/web resources, connection-string reference,
WaitFor, and `ApplyLocalMigrations` env var
- [x] Unit/functional coverage for `/health` and `/alive` endpoints in Testing environment
- [x] Existing MigrationServiceExtensions tests still pass; added `ShouldApplyLocalMigrations` tests
- [x] Unit test: Vimeo clients have no ResilienceHandler, other clients do
- [x] Manual smoke run with Docker: sql/devbetterdb/web Healthy, migrations + seed applied,
`/health` + `/alive` 200, home page 200, structured logs and traces visible in dashboard

## Phase 5 — Docs
- [x] README: "Run with .NET Aspire" section (prereqs: Docker/Podman, `aspire run` or
`dotnet run --project src/DevBetterWeb.AppHost`)

## Phase 6 — Independent review
- [x] Separate agent reviews full diff vs issue
- [x] Address significant findings:
- Fixed: OpenTelemetry gated behind OTLP endpoint (App Insights overlap); README now states
the production resilience change accurately (reCAPTCHA/Google Maps clients get timeouts,
circuit breaker, GET retries)
- Fixed: added Vimeo resilience opt-out test and migration-flag unit tests
- Skipped (follow-up): `DailyCheckService` / `StartupNotificationService` are prod-only
singleton hosted services that inject scoped `IMediator`/`IRepository`; this captive
dependency pre-dates this change (handlers were singletons before) and fixing it means
reworking those services to use `IServiceScopeFactory` — out of scope for #1484.

## Phase 7 — Verification
- [x] `dotnet BuildTestFormat.cs`: build clean, all tests pass (AppHost 4, Functional 5, Tests 118,
Unit 183). Format check fails, but it fails identically on `origin/main` (~11.1k
pre-existing WHITESPACE/IMPORTS/IDE0161 diagnostics in untouched files). All new files
in this change are `dotnet format`-clean; follow-up: repo-wide format pass.
- [x] Open PR with `Fixes #1484`
3 changes: 3 additions & 0 deletions DevBetterWeb.slnx
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,14 @@
<File Path="README.md" />
</Folder>
<Folder Name="/src/">
<Project Path="src/DevBetterWeb.AppHost/DevBetterWeb.AppHost.csproj" />
<Project Path="src/DevBetterWeb.Core/DevBetterWeb.Core.csproj" />
<Project Path="src/DevBetterWeb.Infrastructure/DevBetterWeb.Infrastructure.csproj" />
<Project Path="src/DevBetterWeb.ServiceDefaults/DevBetterWeb.ServiceDefaults.csproj" />
<Project Path="src/DevBetterWeb.Web/DevBetterWeb.Web.csproj" />
</Folder>
<Folder Name="/tests/">
<Project Path="tests/DevBetterWeb.AppHost.Tests/DevBetterWeb.AppHost.Tests.csproj" />
<Project Path="tests/DevBetterWeb.FunctionalTests/DevBetterWeb.FunctionalTests.csproj" />
<Project Path="tests/DevBetterWeb.Tests/DevBetterWeb.Tests.csproj" />
<Project Path="tests/DevBetterWeb.UnitTests/DevBetterWeb.UnitTests.csproj" />
Expand Down
9 changes: 9 additions & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
<PackageVersion Include="Ardalis.SmartEnum" Version="8.2.0" />
<PackageVersion Include="Ardalis.Specification" Version="9.3.1" />
<PackageVersion Include="Ardalis.Specification.EntityFrameworkCore" Version="9.3.1" />
<PackageVersion Include="Aspire.Hosting.SqlServer" Version="13.6.5" />
<PackageVersion Include="Aspire.Hosting.Testing" Version="13.6.5" />
<PackageVersion Include="AutoMapper" Version="17.0.0" />
<PackageVersion Include="coverlet.collector" Version="10.1.0" />
<PackageVersion Include="coverlet.msbuild" Version="10.1.0">
Expand All @@ -39,16 +41,23 @@
<PackageVersion Include="Microsoft.EntityFrameworkCore.Sqlite" Version="11.0.0" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.SqlServer" Version="11.0.0" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Tools" PrivateAssets="all" Version="11.0.0" />
<PackageVersion Include="Microsoft.Extensions.Http.Resilience" Version="11.0.0" />
<PackageVersion Include="Microsoft.Extensions.Identity.Core" Version="11.0.0" />
<PackageVersion Include="Microsoft.Extensions.Identity.Stores" Version="11.0.0" />
<PackageVersion Include="Microsoft.Extensions.Logging.AzureAppServices" Version="11.0.0" />
<PackageVersion Include="Microsoft.Extensions.ServiceDiscovery" Version="11.0.0" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.12.0" />
<PackageVersion Include="Microsoft.Web.LibraryManager.Build" Version="3.0.114" />
<PackageVersion Include="Newtonsoft.Json" Version="13.0.4" />
<PackageVersion Include="NimblePros.ApiClient" Version="2.2.0" />
<PackageVersion Include="NimblePros.Metronome" Version="0.4.1" />
<PackageVersion Include="NimblePros.Vimeo" Version="2.1.2" />
<PackageVersion Include="NSubstitute" Version="6.2.0" />
<PackageVersion Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.21.0" />
<PackageVersion Include="OpenTelemetry.Extensions.Hosting" Version="1.21.0" />
<PackageVersion Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.21.0" />
<PackageVersion Include="OpenTelemetry.Instrumentation.Http" Version="1.21.0" />
<PackageVersion Include="OpenTelemetry.Instrumentation.Runtime" Version="1.21.0" />
<PackageVersion Include="ReportGenerator" Version="5.6.0" />
<PackageVersion Include="Sendgrid" Version="9.29.3" />
<PackageVersion Include="Serilog" Version="4.4.0" />
Expand Down
34 changes: 33 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ Head over to [devBetter.com](https://devbetter.com) to see the live site. Scroll

### Building and Running the App Locally

You can both run the app manually by running the SQL migrations, or by using `docker-compose` see [this section](#run-with-docker)
The easiest way to run the app locally is with [.NET Aspire](#run-with-net-aspire), which starts SQL Server for you and applies migrations automatically. You can also run the app manually by running the SQL migrations, or by using `docker-compose` (see [this section](#run-with-docker)).

- Clone (or Fork and Clone) the repository locally
- Run migrations for both AppDbContext and IdentityDbContext
Expand Down Expand Up @@ -93,6 +93,38 @@ Generate Idempotent Update Script (for production)(from the DevBetter.Web folder
dotnet ef migrations script -c AppDbContext -i -o migrate.sql -p ../DevBetterWeb.Infrastructure/DevBetterWeb.Infrastructure.csproj -s DevBetterWeb.Web.csproj
```

### Run with .NET Aspire

The `DevBetterWeb.AppHost` project orchestrates the app for local development using [.NET Aspire](https://aspire.dev/). It:

- Starts a SQL Server container (`sql`) with a persistent data volume and creates the `DevBetterWeb` database (`devbetterdb`)
- Runs `DevBetterWeb.Web` in the `Development` environment, passing it `ConnectionStrings:DefaultConnection` and waiting for the database to be ready
- Applies the EF Core migrations for both `AppDbContext` and `IdentityDbContext` and seeds test data on startup
- Opens the Aspire dashboard with logs, traces, metrics, and health for every resource

Prerequisites: the .NET 11 SDK and a running container runtime ([Docker Desktop](https://www.docker.com/products/docker-desktop/) or [Podman](https://podman.io/)). The [Aspire CLI](https://aspire.dev/get-started/install-cli/) is optional.

From the root of the repo, run either:

```bash
aspire run
```

or

```bash
dotnet run --project src/DevBetterWeb.AppHost
```

Then open the dashboard login URL printed in the console. The web app is available at `https://localhost:5011` (and `http://localhost:5010`). In Visual Studio or Rider, set `DevBetterWeb.AppHost` as the startup project.

Notes:

- The SQL Server container uses a persistent lifetime and data volume, so it keeps running (and keeps its data) after the AppHost stops, which makes subsequent starts fast. Stop or delete the `sql-*` container and its volume from Docker to reset the database.
- The generated SQL Server `sa` password is stored in the AppHost's user secrets (`Parameters:sql-password`). To connect with a SQL client, use the connection string shown for `devbetterdb` in the dashboard.
- Other settings (Stripe, Vimeo, Discord, email, etc.) still come from the web project's `appsettings.json`/user secrets, as described above.
- `DevBetterWeb.ServiceDefaults` adds OpenTelemetry, health checks (`/health` and `/alive`), HTTP resilience, and service discovery to the web project. OpenTelemetry is only enabled when an OTLP endpoint is configured (as it is under Aspire), so production telemetry (Serilog and Application Insights) is unchanged. HTTP resilience (timeouts, circuit breaker, and retries for safe methods like GET) applies to every `IHttpClientFactory` client in all environments, except the Vimeo clients, which opt out because uploads are long-running.

### Run with Docker

Alternatively you can use `docker-compose` to run the app locally. This is specially helpful when launching the app in operative systems that don't have support for SQL Express like MacOS.
Expand Down
7 changes: 7 additions & 0 deletions src/DevBetterWeb.AppHost/AppHost.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
using DevBetterWeb.AppHost;

var builder = DistributedApplication.CreateBuilder(args);

builder.AddDevBetterWeb();

builder.Build().Run();
22 changes: 22 additions & 0 deletions src/DevBetterWeb.AppHost/DevBetterWeb.AppHost.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<Project Sdk="Aspire.AppHost.Sdk/13.6.5">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net11.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<!-- Use the DCP/dashboard NuGet packages rather than requiring the Aspire CLI bundle,
so `dotnet run` and the AppHost tests work without the Aspire CLI installed. -->
<NoWarn>$(NoWarn);ASPIRE010</NoWarn>
<UserSecretsId>5f0f3c55-6a43-4a0e-9a0b-2f3b1e4d1484</UserSecretsId>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Aspire.Hosting.SqlServer" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\DevBetterWeb.Web\DevBetterWeb.Web.csproj" />
</ItemGroup>

</Project>
35 changes: 35 additions & 0 deletions src/DevBetterWeb.AppHost/DevBetterWebAppModel.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using Aspire.Hosting;
using Aspire.Hosting.ApplicationModel;

namespace DevBetterWeb.AppHost;

public static class DevBetterWebAppModel
{
public const string SqlServerResourceName = "sql";
public const string DatabaseResourceName = "devbetterdb";
public const string DatabaseName = "DevBetterWeb";
public const string WebResourceName = "web";

// Matches DevBetterWeb.Core.Constants.DEFAULT_CONNECTION_STRING_NAME so the web project
// picks up ConnectionStrings:DefaultConnection without any code changes.
public const string ConnectionStringName = "DefaultConnection";

public const string ApplyLocalMigrationsKey = "ApplyLocalMigrations";

public static IDistributedApplicationBuilder AddDevBetterWeb(this IDistributedApplicationBuilder builder)
{
var sql = builder.AddSqlServer(SqlServerResourceName)
.WithDataVolume()
.WithLifetime(ContainerLifetime.Persistent);

var database = sql.AddDatabase(DatabaseResourceName, DatabaseName);

builder.AddProject<Projects.DevBetterWeb_Web>(WebResourceName, launchProfileName: "DevBetterWeb.Web - DEV")
.WithReference(database, ConnectionStringName)
.WaitFor(database)
.WithEnvironment(ApplyLocalMigrationsKey, "true")
.WithHttpHealthCheck("/health");

return builder;
}
}
30 changes: 30 additions & 0 deletions src/DevBetterWeb.AppHost/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"profiles": {
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:17112;http://localhost:15204",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"DOTNET_ENVIRONMENT": "Development",
"ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21006",
"ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22154"
}
},
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:15204",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"DOTNET_ENVIRONMENT": "Development",
"ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19004",
"ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20160",
"ASPIRE_ALLOW_UNSECURED_TRANSPORT": "true"
}
}
}
}
8 changes: 8 additions & 0 deletions src/DevBetterWeb.AppHost/appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
9 changes: 9 additions & 0 deletions src/DevBetterWeb.AppHost/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"Aspire.Hosting.Dcp": "Warning"
}
}
}
5 changes: 5 additions & 0 deletions src/DevBetterWeb.AppHost/aspire.config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"appHost": {
"path": "DevBetterWeb.AppHost.csproj"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
<ItemGroup>
<PackageReference Include="Ardalis.Specification.EntityFrameworkCore" />
<PackageReference Include="Markdig" />
<PackageReference Include="Microsoft.Extensions.Http.Resilience" />
<PackageReference Include="Mediator.Abstractions" />
<PackageReference Include="NimblePros.Vimeo" />
<PackageReference Include="Ardalis.EFCore.Extensions" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,15 @@ public static IServiceCollection RegisterVimeoServicesDependencies(this IService
client.Timeout = TimeSpan.FromMinutes(60);
};

// Register named HttpClients for injection
services.AddHttpClient("VimeoApi", configureVimeoApi);
services.AddHttpClient("VimeoOEmbed", configureVimeoOEmbed);
services.AddHttpClient("VimeoTusApi", configureVimeoTus);
// Register named HttpClients for injection.
// Vimeo uploads are long-running (60 minute client timeouts) and chunked TUS PATCHes are
// not safely retryable, so opt these clients out of the default resilience pipeline that
// ServiceDefaults adds to every HttpClient (its 30 second total timeout would break uploads).
#pragma warning disable EXTEXP0001 // RemoveAllResilienceHandlers is marked experimental
services.AddHttpClient("VimeoApi", configureVimeoApi).RemoveAllResilienceHandlers();
services.AddHttpClient("VimeoOEmbed", configureVimeoOEmbed).RemoveAllResilienceHandlers();
services.AddHttpClient("VimeoTusApi", configureVimeoTus).RemoveAllResilienceHandlers();
#pragma warning restore EXTEXP0001

// Register ClientApiConfigurations (used by NimblePros.Vimeo)
var clientConfigs = new ClientApiConfigurations()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net11.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsAspireSharedProject>true</IsAspireSharedProject>
</PropertyGroup>

<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />

<PackageReference Include="Microsoft.Extensions.Http.Resilience" />
<PackageReference Include="Microsoft.Extensions.ServiceDiscovery" />
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" />
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" />
<PackageReference Include="OpenTelemetry.Instrumentation.Http" />
<PackageReference Include="OpenTelemetry.Instrumentation.Runtime" />
</ItemGroup>

</Project>
Loading
Loading