diff --git a/.claude/plans/2026-11-15-issue-1484-add-aspire.md b/.claude/plans/2026-11-15-issue-1484-add-aspire.md new file mode 100644 index 000000000..1ba92b5db --- /dev/null +++ b/.claude/plans/2026-11-15-issue-1484-add-aspire.md @@ -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 consuming scoped + IHandle). 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` diff --git a/DevBetterWeb.slnx b/DevBetterWeb.slnx index 80a587eb5..a79f14624 100644 --- a/DevBetterWeb.slnx +++ b/DevBetterWeb.slnx @@ -18,11 +18,14 @@ + + + diff --git a/Directory.Packages.props b/Directory.Packages.props index 62240741b..a0e928c26 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -14,6 +14,8 @@ + + @@ -39,9 +41,11 @@ + + @@ -49,6 +53,11 @@ + + + + + diff --git a/README.md b/README.md index 371d1e185..b8b6912af 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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. diff --git a/src/DevBetterWeb.AppHost/AppHost.cs b/src/DevBetterWeb.AppHost/AppHost.cs new file mode 100644 index 000000000..9b2bb2049 --- /dev/null +++ b/src/DevBetterWeb.AppHost/AppHost.cs @@ -0,0 +1,7 @@ +using DevBetterWeb.AppHost; + +var builder = DistributedApplication.CreateBuilder(args); + +builder.AddDevBetterWeb(); + +builder.Build().Run(); diff --git a/src/DevBetterWeb.AppHost/DevBetterWeb.AppHost.csproj b/src/DevBetterWeb.AppHost/DevBetterWeb.AppHost.csproj new file mode 100644 index 000000000..9cb34f31e --- /dev/null +++ b/src/DevBetterWeb.AppHost/DevBetterWeb.AppHost.csproj @@ -0,0 +1,22 @@ + + + + Exe + net11.0 + enable + enable + + $(NoWarn);ASPIRE010 + 5f0f3c55-6a43-4a0e-9a0b-2f3b1e4d1484 + + + + + + + + + + + diff --git a/src/DevBetterWeb.AppHost/DevBetterWebAppModel.cs b/src/DevBetterWeb.AppHost/DevBetterWebAppModel.cs new file mode 100644 index 000000000..0a09aae44 --- /dev/null +++ b/src/DevBetterWeb.AppHost/DevBetterWebAppModel.cs @@ -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(WebResourceName, launchProfileName: "DevBetterWeb.Web - DEV") + .WithReference(database, ConnectionStringName) + .WaitFor(database) + .WithEnvironment(ApplyLocalMigrationsKey, "true") + .WithHttpHealthCheck("/health"); + + return builder; + } +} diff --git a/src/DevBetterWeb.AppHost/Properties/launchSettings.json b/src/DevBetterWeb.AppHost/Properties/launchSettings.json new file mode 100644 index 000000000..1e91c4953 --- /dev/null +++ b/src/DevBetterWeb.AppHost/Properties/launchSettings.json @@ -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" + } + } + } +} diff --git a/src/DevBetterWeb.AppHost/appsettings.Development.json b/src/DevBetterWeb.AppHost/appsettings.Development.json new file mode 100644 index 000000000..0c208ae91 --- /dev/null +++ b/src/DevBetterWeb.AppHost/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/src/DevBetterWeb.AppHost/appsettings.json b/src/DevBetterWeb.AppHost/appsettings.json new file mode 100644 index 000000000..31c092aa4 --- /dev/null +++ b/src/DevBetterWeb.AppHost/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Aspire.Hosting.Dcp": "Warning" + } + } +} diff --git a/src/DevBetterWeb.AppHost/aspire.config.json b/src/DevBetterWeb.AppHost/aspire.config.json new file mode 100644 index 000000000..1b4dbd7af --- /dev/null +++ b/src/DevBetterWeb.AppHost/aspire.config.json @@ -0,0 +1,5 @@ +{ + "appHost": { + "path": "DevBetterWeb.AppHost.csproj" + } +} diff --git a/src/DevBetterWeb.Infrastructure/DevBetterWeb.Infrastructure.csproj b/src/DevBetterWeb.Infrastructure/DevBetterWeb.Infrastructure.csproj index d9e282720..cf48a0e80 100644 --- a/src/DevBetterWeb.Infrastructure/DevBetterWeb.Infrastructure.csproj +++ b/src/DevBetterWeb.Infrastructure/DevBetterWeb.Infrastructure.csproj @@ -18,6 +18,7 @@ + diff --git a/src/DevBetterWeb.Infrastructure/VimeoServiceCollectionExtensions.cs b/src/DevBetterWeb.Infrastructure/VimeoServiceCollectionExtensions.cs index bc53d02ee..6cbe8470e 100644 --- a/src/DevBetterWeb.Infrastructure/VimeoServiceCollectionExtensions.cs +++ b/src/DevBetterWeb.Infrastructure/VimeoServiceCollectionExtensions.cs @@ -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() diff --git a/src/DevBetterWeb.ServiceDefaults/DevBetterWeb.ServiceDefaults.csproj b/src/DevBetterWeb.ServiceDefaults/DevBetterWeb.ServiceDefaults.csproj new file mode 100644 index 000000000..406ef5def --- /dev/null +++ b/src/DevBetterWeb.ServiceDefaults/DevBetterWeb.ServiceDefaults.csproj @@ -0,0 +1,22 @@ + + + + net11.0 + enable + enable + true + + + + + + + + + + + + + + + diff --git a/src/DevBetterWeb.ServiceDefaults/Extensions.cs b/src/DevBetterWeb.ServiceDefaults/Extensions.cs new file mode 100644 index 000000000..8ad949d89 --- /dev/null +++ b/src/DevBetterWeb.ServiceDefaults/Extensions.cs @@ -0,0 +1,111 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Diagnostics.HealthChecks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Diagnostics.HealthChecks; +using Microsoft.Extensions.Http.Resilience; +using Microsoft.Extensions.Logging; +using OpenTelemetry; +using OpenTelemetry.Metrics; +using OpenTelemetry.Trace; + +namespace Microsoft.Extensions.Hosting; + +// Adds common Aspire services: service discovery, resilience, health checks, and OpenTelemetry. +// To learn more about using this project, see https://aka.ms/aspire/service-defaults +public static class Extensions +{ + public const string HealthEndpointPath = "/health"; + public const string AlivenessEndpointPath = "/alive"; + public const string OtlpEndpointConfigKey = "OTEL_EXPORTER_OTLP_ENDPOINT"; + + public static TBuilder AddServiceDefaults(this TBuilder builder) where TBuilder : IHostApplicationBuilder + { + builder.ConfigureOpenTelemetry(); + + builder.AddDefaultHealthChecks(); + + builder.Services.AddServiceDiscovery(); + + builder.Services.ConfigureHttpClientDefaults(http => + { + // Turn on resilience by default, but never retry non-idempotent requests + // (POST/PUT/PATCH/DELETE) such as payments, webhooks, and emails. + http.AddStandardResilienceHandler(options => options.Retry.DisableForUnsafeHttpMethods()); + + // Turn on service discovery by default + http.AddServiceDiscovery(); + }); + + return builder; + } + + public static bool IsOtlpExporterEnabled(this IHostApplicationBuilder builder) => + !string.IsNullOrWhiteSpace(builder.Configuration[OtlpEndpointConfigKey]); + + public static TBuilder ConfigureOpenTelemetry(this TBuilder builder) where TBuilder : IHostApplicationBuilder + { + // Only wire up OpenTelemetry when an OTLP endpoint is configured (e.g. under the Aspire AppHost). + // Application Insights 3.x is itself built on OpenTelemetry, so registering instrumentation + // unconditionally would change what production sends to Azure Monitor (extra metrics, and + // health check requests filtered out of request telemetry). + if (!builder.IsOtlpExporterEnabled()) + { + return builder; + } + + builder.Logging.AddOpenTelemetry(logging => + { + logging.IncludeFormattedMessage = true; + logging.IncludeScopes = true; + }); + + builder.Services.AddOpenTelemetry() + .WithMetrics(metrics => + { + metrics.AddAspNetCoreInstrumentation() + .AddHttpClientInstrumentation() + .AddRuntimeInstrumentation(); + }) + .WithTracing(tracing => + { + tracing.AddSource(builder.Environment.ApplicationName) + .AddAspNetCoreInstrumentation(tracing => + // Exclude health check requests from tracing + tracing.Filter = context => + !context.Request.Path.StartsWithSegments(HealthEndpointPath) + && !context.Request.Path.StartsWithSegments(AlivenessEndpointPath) + ) + .AddHttpClientInstrumentation(); + }) + .UseOtlpExporter(); + + return builder; + } + + public static TBuilder AddDefaultHealthChecks(this TBuilder builder) where TBuilder : IHostApplicationBuilder + { + builder.Services.AddHealthChecks() + // Add a default liveness check to ensure app is responsive + .AddCheck("self", () => HealthCheckResult.Healthy(), ["live"]); + + return builder; + } + + public static WebApplication MapDefaultEndpoints(this WebApplication app) + { + // Unlike the Aspire template, these are mapped in every environment because the + // production site already exposes /health for its hosting platform's probes. + // Only the default (non-detailed) response writer is used, so no check details leak. + + // All health checks must pass for app to be considered ready to accept traffic after starting + app.MapHealthChecks(HealthEndpointPath); + + // Only health checks tagged with the "live" tag must pass for app to be considered alive + app.MapHealthChecks(AlivenessEndpointPath, new HealthCheckOptions + { + Predicate = r => r.Tags.Contains("live") + }); + + return app; + } +} diff --git a/src/DevBetterWeb.Web/DevBetterWeb.Web.csproj b/src/DevBetterWeb.Web/DevBetterWeb.Web.csproj index 126eff12a..ac851a3db 100644 --- a/src/DevBetterWeb.Web/DevBetterWeb.Web.csproj +++ b/src/DevBetterWeb.Web/DevBetterWeb.Web.csproj @@ -62,6 +62,7 @@ + diff --git a/src/DevBetterWeb.Web/MigrationServiceExtensions.cs b/src/DevBetterWeb.Web/MigrationServiceExtensions.cs index f80dea2d7..7705f1630 100644 --- a/src/DevBetterWeb.Web/MigrationServiceExtensions.cs +++ b/src/DevBetterWeb.Web/MigrationServiceExtensions.cs @@ -5,14 +5,21 @@ namespace DevBetterWeb.Web; public static class MigrationServiceExtensions { + /// + /// Local migrations run when the app is in a docker-compose container or when the Aspire + /// AppHost sets the ApplyLocalMigrations flag. They still only run in Development. + /// + public static bool ShouldApplyLocalMigrations(bool runningInContainer, bool applyLocalMigrationsFlag) => + runningInContainer || applyLocalMigrationsFlag; + public static async Task ApplyLocalMigrationAsync( this ILocalMigrationService migrationService, string environmentName, - bool runningIncontainer) + bool shouldApplyMigrations) where TContext : DbContext { if (environmentName is not "Development" - || !runningIncontainer) + || !shouldApplyMigrations) { return; } diff --git a/src/DevBetterWeb.Web/Program.cs b/src/DevBetterWeb.Web/Program.cs index 2da240f4a..a61723157 100644 --- a/src/DevBetterWeb.Web/Program.cs +++ b/src/DevBetterWeb.Web/Program.cs @@ -42,15 +42,30 @@ string vimeoToken = builder.Configuration["Vimeo:Token"] ?? ""; var isTesting = builder.Environment.IsEnvironment("Testing"); +// When running under Aspire (an OTLP endpoint is configured), forward Serilog events to the +// registered logger providers so the OpenTelemetry provider exports them to the dashboard. +// Serilog already writes to the console/file/SQL sinks, so clear the built-in providers first +// (Serilog bypasses provider filters when forwarding) and let AddServiceDefaults add OpenTelemetry. +bool forwardLogsToProviders = builder.IsOtlpExporterEnabled(); +if (forwardLogsToProviders) +{ + builder.Logging.ClearProviders(); +} + +// Aspire service defaults: OpenTelemetry, health checks, resilience, service discovery +builder.AddServiceDefaults(); + // builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory()); if (!isTesting) { - builder.Host.UseSerilog((_, config) => config.ReadFrom.Configuration(builder.Configuration)); + builder.Host.UseSerilog((_, config) => config.ReadFrom.Configuration(builder.Configuration), + writeToProviders: forwardLogsToProviders); } else { - builder.Host.UseSerilog((_, config) => config.MinimumLevel.Information().WriteTo.Console()); + builder.Host.UseSerilog((_, config) => config.MinimumLevel.Information().WriteTo.Console(), + writeToProviders: forwardLogsToProviders); } builder.Services.Configure(options => { @@ -93,6 +108,9 @@ builder.Services.AddMediator(options => { + // Handlers (e.g. DomainEventHandler) depend on scoped services such as repositories and + // DbContexts, so they must not be singletons (Mediator's default lifetime). + options.ServiceLifetime = ServiceLifetime.Scoped; options.Assemblies = [ typeof(IAggregateRoot), @@ -156,8 +174,6 @@ builder.Services.AddHttpClient(); -builder.Services.AddHealthChecks(); - builder.Services.AddMvc() .AddControllersAsServices(); @@ -209,7 +225,7 @@ }); } -app.MapHealthChecks("/health"); +app.MapDefaultEndpoints(); app.MapRazorPages(); @@ -283,9 +299,12 @@ async Task ApplyLocalMigrationsAsync(WebApplication webApplication) var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? string.Empty; bool.TryParse(Environment.GetEnvironmentVariable("DOTNET_RUNNING_IN_CONTAINER"), out var runningInContainer); + // Set by the Aspire AppHost so a fresh local SQL Server container gets migrated on startup. + bool applyLocalMigrations = webApplication.Configuration.GetValue("ApplyLocalMigrations"); + bool shouldApplyMigrations = MigrationServiceExtensions.ShouldApplyLocalMigrations(runningInContainer, applyLocalMigrations); - await identity.ApplyLocalMigrationAsync(environment, runningInContainer); - await app.ApplyLocalMigrationAsync(environment, runningInContainer); + await identity.ApplyLocalMigrationAsync(environment, shouldApplyMigrations); + await app.ApplyLocalMigrationAsync(environment, shouldApplyMigrations); } // Make the implicit Program.cs class public, so integration tests can reference the correct assembly for host building diff --git a/tests/DevBetterWeb.AppHost.Tests/AppModelTests.cs b/tests/DevBetterWeb.AppHost.Tests/AppModelTests.cs new file mode 100644 index 000000000..026f50115 --- /dev/null +++ b/tests/DevBetterWeb.AppHost.Tests/AppModelTests.cs @@ -0,0 +1,81 @@ +using Aspire.Hosting; +using Aspire.Hosting.ApplicationModel; +using Aspire.Hosting.Testing; +using DevBetterWeb.AppHost; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; +using Shouldly; +using Xunit; + +namespace DevBetterWeb.AppHost.Tests; + +// These tests build the Aspire application model without starting it, so they do not need +// Docker/Podman and are safe to run in CI. +public class AppModelTests +{ + private static async Task BuildModelAsync() + { + var appHost = await DistributedApplicationTestingBuilder.CreateAsync(); + var app = await appHost.BuildAsync(); + return app.Services.GetRequiredService(); + } + + [Fact] + public async Task DefinesSqlServerWithPersistentDataVolume() + { + var model = await BuildModelAsync(); + + var sql = model.Resources.OfType() + .Single(r => r.Name == DevBetterWebAppModel.SqlServerResourceName); + + sql.Annotations.OfType() + .ShouldContain(m => m.Type == ContainerMountType.Volume); + sql.Annotations.OfType() + .ShouldContain(l => l.Lifetime == ContainerLifetime.Persistent); + } + + [Fact] + public async Task DefinesDevBetterWebDatabase() + { + var model = await BuildModelAsync(); + + var database = model.Resources.OfType() + .Single(r => r.Name == DevBetterWebAppModel.DatabaseResourceName); + + database.DatabaseName.ShouldBe(DevBetterWebAppModel.DatabaseName); + database.Parent.Name.ShouldBe(DevBetterWebAppModel.SqlServerResourceName); + } + + [Fact] + public async Task WebWaitsForDatabase() + { + var model = await BuildModelAsync(); + var web = GetWeb(model); + + web.Annotations.OfType() + .ShouldContain(w => w.Resource.Name == DevBetterWebAppModel.DatabaseResourceName); + } + + [Fact] + public async Task WebReceivesDefaultConnectionStringAndMigrationFlag() + { + var model = await BuildModelAsync(); + var web = GetWeb(model); + + // Publish mode resolves connection strings to expressions, so no endpoints need allocating. + var configuration = await ExecutionConfigurationBuilder.Create(web) + .WithEnvironmentVariablesConfig() + .BuildAsync( + new DistributedApplicationExecutionContext(DistributedApplicationOperation.Publish), + NullLogger.Instance, + CancellationToken.None); + var environment = configuration.EnvironmentVariables.ToDictionary(kv => kv.Key, kv => kv.Value); + + environment.Keys.ShouldContain($"ConnectionStrings__{DevBetterWebAppModel.ConnectionStringName}"); + environment[DevBetterWebAppModel.ApplyLocalMigrationsKey].ShouldBe("true"); + } + + private static ProjectResource GetWeb(DistributedApplicationModel model) => + model.Resources.OfType() + .Single(r => r.Name == DevBetterWebAppModel.WebResourceName); +} diff --git a/tests/DevBetterWeb.AppHost.Tests/DevBetterWeb.AppHost.Tests.csproj b/tests/DevBetterWeb.AppHost.Tests/DevBetterWeb.AppHost.Tests.csproj new file mode 100644 index 000000000..8754bf551 --- /dev/null +++ b/tests/DevBetterWeb.AppHost.Tests/DevBetterWeb.AppHost.Tests.csproj @@ -0,0 +1,25 @@ + + + net11.0 + enable + enable + false + + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + diff --git a/tests/DevBetterWeb.FunctionalTests/Endpoints/HealthEndpointsGet.cs b/tests/DevBetterWeb.FunctionalTests/Endpoints/HealthEndpointsGet.cs new file mode 100644 index 000000000..c9656afd2 --- /dev/null +++ b/tests/DevBetterWeb.FunctionalTests/Endpoints/HealthEndpointsGet.cs @@ -0,0 +1,27 @@ +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +using Xunit; + +namespace DevBetterWeb.FunctionalTests.Endpoints; + +public class HealthEndpointsGet : IClassFixture> +{ + private readonly HttpClient _client; + + public HealthEndpointsGet(CustomWebApplicationFactory factory) + { + _client = factory.CreateClient(); + } + + [Theory] + [InlineData("/health")] + [InlineData("/alive")] + public async Task ReturnsHealthy(string path) + { + HttpResponseMessage response = await _client.GetAsync(path); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("Healthy", await response.Content.ReadAsStringAsync()); + } +} diff --git a/tests/DevBetterWeb.UnitTests/Infrastructure/Vimeo/VimeoHttpClientResilienceTests.cs b/tests/DevBetterWeb.UnitTests/Infrastructure/Vimeo/VimeoHttpClientResilienceTests.cs new file mode 100644 index 000000000..be733c439 --- /dev/null +++ b/tests/DevBetterWeb.UnitTests/Infrastructure/Vimeo/VimeoHttpClientResilienceTests.cs @@ -0,0 +1,59 @@ +using System; +using System.Collections.Generic; +using System.Net.Http; +using DevBetterWeb.Infrastructure; +using Microsoft.Extensions.DependencyInjection; +using Xunit; + +namespace DevBetterWeb.UnitTests.Infrastructure.Vimeo; + +// ServiceDefaults adds the standard resilience handler (30 second total timeout) to every +// HttpClient. Vimeo uploads are long-running, so the Vimeo clients must opt out of it. +public class VimeoHttpClientResilienceTests +{ + private const string ResilienceHandlerTypeName = "ResilienceHandler"; + + private static IHttpMessageHandlerFactory BuildHandlerFactory() + { + var services = new ServiceCollection(); + services.AddLogging(); + services.ConfigureHttpClientDefaults(http => http.AddStandardResilienceHandler()); + services.AddHttpClient("SomeOtherClient"); + services.RegisterVimeoServicesDependencies("test-token"); + + return services.BuildServiceProvider().GetRequiredService(); + } + + private static IEnumerable GetHandlerChainTypes(HttpMessageHandler handler) + { + HttpMessageHandler? current = handler; + while (current is not null) + { + yield return current.GetType(); + current = (current as DelegatingHandler)?.InnerHandler; + } + } + + [Fact] + public void DefaultClientsGetResilienceHandler() + { + var factory = BuildHandlerFactory(); + + var chain = GetHandlerChainTypes(factory.CreateHandler("SomeOtherClient")); + + Assert.Contains(chain, t => t.Name == ResilienceHandlerTypeName); + } + + [Theory] + [InlineData("VimeoApi")] + [InlineData("VimeoOEmbed")] + [InlineData("VimeoTusApi")] + public void VimeoClientsDoNotGetResilienceHandler(string clientName) + { + var factory = BuildHandlerFactory(); + + var chain = GetHandlerChainTypes(factory.CreateHandler(clientName)); + + Assert.DoesNotContain(chain, t => t.Name == ResilienceHandlerTypeName); + } +} diff --git a/tests/DevBetterWeb.UnitTests/Web/Extensions/MigrationServiceExtensionsTests.cs b/tests/DevBetterWeb.UnitTests/Web/Extensions/MigrationServiceExtensionsTests.cs index 8fa588eb0..d72d544d7 100644 --- a/tests/DevBetterWeb.UnitTests/Web/Extensions/MigrationServiceExtensionsTests.cs +++ b/tests/DevBetterWeb.UnitTests/Web/Extensions/MigrationServiceExtensionsTests.cs @@ -22,4 +22,19 @@ public async Task OnlyMigratesWhenEnvironmentIsDevelopment( await migrationService.Received(expectedRuns).ApplyDatabaseMigrationsAsync(); } + + [Theory] + [InlineData(false, false, false)] + [InlineData(true, false, true)] + [InlineData(false, true, true)] + [InlineData(true, true, true)] + public void ShouldApplyLocalMigrationsWhenInContainerOrFlagSet( + bool runningInContainer, + bool applyLocalMigrationsFlag, + bool expected) + { + bool result = MigrationServiceExtensions.ShouldApplyLocalMigrations(runningInContainer, applyLocalMigrationsFlag); + + Assert.Equal(expected, result); + } }