From 6af3d4f5e53ce785a3e212332eb30bdf9e493b93 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Sat, 22 Aug 2026 06:27:42 -0700 Subject: [PATCH] Adds OpenTelemetry pipelines and health probes to the presentation layer --- .../PresentationApiLayerServices.cs | 6 ++ .../PresentationApiTelemetryServices.cs | 102 ++++++++++++++++++ .../HealthChecks/DatabaseHealthCheck.cs | 48 +++++++++ .../Lumina.Presentation.Api.csproj | 7 ++ src/Lumina.Presentation.Api/Program.cs | 42 +++++++- src/Lumina.Presentation.Api/appsettings.json | 20 ++-- .../PresentationWebTelemetryServices.cs | 102 ++++++++++++++++++ .../ApiReachabilityHealthCheck.cs | 55 ++++++++++ .../Common/Telemetry/WebTelemetry.cs | 21 ++++ .../Lumina.Presentation.Web.csproj | 7 ++ src/Lumina.Presentation.Web/Program.cs | 11 ++ src/Lumina.Presentation.Web/appsettings.json | 20 ++-- .../Core/Health/FailingDatabaseApiFactory.cs | 32 ++++++ .../Core/Health/FailingDatabaseHealthCheck.cs | 33 ++++++ .../Core/Health/HealthEndpointFailureTests.cs | 37 +++++++ .../Core/Health/HealthEndpointTests.cs | 68 ++++++++++++ .../HealthyApiReachabilityHealthCheck.cs | 37 +++++++ .../Common/Setup/LuminaWebFactory.cs | 7 ++ .../Core/Health/FailingApiHealthFactory.cs | 31 ++++++ .../Core/Health/HealthEndpointFailureTests.cs | 41 +++++++ .../Core/Health/HealthEndpointTests.cs | 56 ++++++++++ .../UnhealthyApiReachabilityHealthCheck.cs | 37 +++++++ 22 files changed, 800 insertions(+), 20 deletions(-) create mode 100644 src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiTelemetryServices.cs create mode 100644 src/Lumina.Presentation.Api/Common/HealthChecks/DatabaseHealthCheck.cs create mode 100644 src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebTelemetryServices.cs create mode 100644 src/Lumina.Presentation.Web/Common/HealthChecks/ApiReachabilityHealthCheck.cs create mode 100644 src/Lumina.Presentation.Web/Common/Telemetry/WebTelemetry.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Health/FailingDatabaseApiFactory.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Health/FailingDatabaseHealthCheck.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Health/HealthEndpointFailureTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Health/HealthEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Common/Setup/HealthyApiReachabilityHealthCheck.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Health/FailingApiHealthFactory.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Health/HealthEndpointFailureTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Health/HealthEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Health/UnhealthyApiReachabilityHealthCheck.cs diff --git a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs index aa914527..920f999a 100644 --- a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs +++ b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs @@ -3,6 +3,7 @@ using FastEndpoints; using FastEndpoints.Swagger; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Presentation.Api.Common.Authentication; +using Lumina.Presentation.Api.Common.HealthChecks; using MessagePack; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; @@ -10,6 +11,7 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Json; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Logging; using Microsoft.IdentityModel.Tokens; using System; @@ -39,6 +41,10 @@ public static class PresentationApiLayerServices services.AddMemoryCache(); // used for the tracking involved in authentication rate limiting services.AddProblemDetails(); + // the readiness health check verifies that the database can be reached, and is probed by container orchestrators and load balancers + services.AddHealthChecks() + .AddCheck("database", HealthStatus.Unhealthy, ["ready"]); + services.Configure(jsonOptions => { jsonOptions.SerializerOptions.Converters.Add(new JsonStringEnumConverter()); diff --git a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiTelemetryServices.cs b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiTelemetryServices.cs new file mode 100644 index 00000000..b7ef7ec7 --- /dev/null +++ b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiTelemetryServices.cs @@ -0,0 +1,102 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Telemetry; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using OpenTelemetry; +using OpenTelemetry.Metrics; +using OpenTelemetry.Resources; +using OpenTelemetry.Trace; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Common.DependencyInjection; + +/// +/// Contains the OpenTelemetry services of the Presentation API layer. +/// +[ExcludeFromCodeCoverage] +public static class PresentationApiTelemetryServices +{ + private const string SERVICE_NAME = "Lumina.Api"; + private const string ENTITY_FRAMEWORK_CORE_METER_NAME = "Microsoft.EntityFrameworkCore"; + + /// + /// Registers the OpenTelemetry tracing and metrics pipelines into the dependency injection container. + /// + /// The service collection to add the services to. + /// Application configuration properties. + /// The hosting environment of the application. + /// The updated . + public static IServiceCollection AddPresentationApiTelemetryServices(this IServiceCollection services, IConfiguration configuration, IWebHostEnvironment environment) + { + bool isTelemetryEnabled = configuration.GetValue("Telemetry:Enabled") ?? true; + if (!isTelemetryEnabled) + return services; + + bool isConsoleExporterEnabled = configuration.GetValue("Telemetry:ConsoleExporterEnabled") ?? environment.IsDevelopment(); + string? otlpEndpoint = GetOtlpEndpoint(configuration); + double traceSampleRatio = configuration.GetValue("Telemetry:TraceSampleRatio") ?? 1.0; + string serviceVersion = typeof(Program).Assembly.GetName().Version?.ToString() ?? "unknown"; + + services.AddOpenTelemetry() + .ConfigureResource(resourceBuilder => resourceBuilder + .AddService(serviceName: SERVICE_NAME, serviceVersion: serviceVersion) + .AddEnvironmentVariableDetector() + .AddAttributes(new Dictionary + { + ["deployment.environment"] = environment.EnvironmentName + })) + .WithTracing(tracingBuilder => + { + tracingBuilder.SetSampler(CreateSampler(traceSampleRatio)); + tracingBuilder.AddSource(ApplicationTelemetry.SOURCE_NAME); + tracingBuilder.AddAspNetCoreInstrumentation(); + if (isConsoleExporterEnabled) + tracingBuilder.AddConsoleExporter(); + if (otlpEndpoint is not null) + tracingBuilder.AddOtlpExporter(otlpExporterOptions => otlpExporterOptions.Endpoint = new Uri(otlpEndpoint)); + }) + .WithMetrics(metricsBuilder => + { + metricsBuilder.AddMeter(ApplicationTelemetry.SOURCE_NAME); + metricsBuilder.AddMeter(ENTITY_FRAMEWORK_CORE_METER_NAME); + metricsBuilder.AddAspNetCoreInstrumentation(); + metricsBuilder.AddRuntimeInstrumentation(); + if (isConsoleExporterEnabled) + metricsBuilder.AddConsoleExporter(); + if (otlpEndpoint is not null) + metricsBuilder.AddOtlpExporter(otlpExporterOptions => otlpExporterOptions.Endpoint = new Uri(otlpEndpoint)); + }); + + return services; + } + + /// + /// Gets the OTLP exporter endpoint from configuration, falling back to the standard OTEL_EXPORTER_OTLP_ENDPOINT environment variable. + /// + /// Application configuration properties. + /// The OTLP endpoint, or when no endpoint is configured. + private static string? GetOtlpEndpoint(IConfiguration configuration) + { + string? endpoint = configuration.GetValue("Telemetry:Otlp:Endpoint"); + if (string.IsNullOrWhiteSpace(endpoint)) + endpoint = Environment.GetEnvironmentVariable("OTEL_EXPORTER_OTLP_ENDPOINT"); + return string.IsNullOrWhiteSpace(endpoint) ? null : endpoint; + } + + /// + /// Creates the trace sampler used by the API, sampling every trace by default and honoring the configured ratio for production traffic. + /// + /// The ratio of traces to sample, in the range of zero to one. + /// The configured trace sampler. + private static Sampler CreateSampler(double traceSampleRatio) + { + return traceSampleRatio < 1.0 + ? new ParentBasedSampler(new TraceIdRatioBasedSampler(traceSampleRatio)) + : new AlwaysOnSampler(); + } +} diff --git a/src/Lumina.Presentation.Api/Common/HealthChecks/DatabaseHealthCheck.cs b/src/Lumina.Presentation.Api/Common/HealthChecks/DatabaseHealthCheck.cs new file mode 100644 index 00000000..9ff53c7d --- /dev/null +++ b/src/Lumina.Presentation.Api/Common/HealthChecks/DatabaseHealthCheck.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Diagnostics.HealthChecks; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Common.HealthChecks; + +/// +/// Health check that verifies the database can be reached. +/// +public class DatabaseHealthCheck : IHealthCheck +{ + private readonly LuminaDbContext _dbContext; + + /// + /// Initializes a new instance of the class. + /// + /// Injected database context. + public DatabaseHealthCheck(LuminaDbContext dbContext) + { + _dbContext = dbContext; + } + + /// + /// Checks whether the database can be reached. + /// + /// The health check context. + /// Token to monitor for cancellation requests. + /// A task that represents the asynchronous operation, containing the health check result. + public virtual async Task CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken) + { + try + { + bool canConnect = await _dbContext.Database.CanConnectAsync(cancellationToken).ConfigureAwait(false); + return canConnect + ? HealthCheckResult.Healthy() + : HealthCheckResult.Unhealthy("The database is not reachable."); + } + catch (Exception exception) + { + return HealthCheckResult.Unhealthy("The database is not reachable.", exception); + } + } +} diff --git a/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj b/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj index da5dda00..76e93fc8 100644 --- a/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj +++ b/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj @@ -31,10 +31,17 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + diff --git a/src/Lumina.Presentation.Api/Program.cs b/src/Lumina.Presentation.Api/Program.cs index abe2bbd1..41052581 100644 --- a/src/Lumina.Presentation.Api/Program.cs +++ b/src/Lumina.Presentation.Api/Program.cs @@ -12,11 +12,14 @@ using Lumina.Presentation.Api.Common.DependencyInjection; using Lumina.Presentation.Api.Common.Middlewares; using Lumina.Presentation.Api.Common.Utilities; using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.Logging; using Scalar.AspNetCore; @@ -24,6 +27,7 @@ using Serilog; using System; using System.Diagnostics.CodeAnalysis; using System.IO; +using System.Linq; using System.Threading.Tasks; #endregion @@ -47,6 +51,7 @@ public class Program builder.Services.BindPresentationApiLayerConfiguration(builder.Configuration); builder.Services.AddPresentationApiLayerServices(builder.Configuration); + builder.Services.AddPresentationApiTelemetryServices(builder.Configuration, builder.Environment); builder.Services.AddApplicationLayerServices(); builder.Services.AddInfrastructureLayerServices(builder.Configuration); builder.Services.AddDataAccessLayerServices(); @@ -137,8 +142,9 @@ public class Program .WithDotNetFlag(true); }); - // add the middleware that fires domain events and ensures eventual transactional consistency, but NOT for long-polling/WebSockets stuff like SignalR, which would keep the db locked - app.UseWhen(ctx => !ctx.Request.Path.StartsWithSegments("/scanProgressHub"), app => app.UseMiddleware()); + // add the middleware that fires domain events and ensures eventual transactional consistency, but NOT for long-polling/WebSockets stuff like SignalR, which would keep the db locked, + // and NOT for the health probes, which would otherwise begin a database transaction on every probe + app.UseWhen(ctx => !ctx.Request.Path.StartsWithSegments("/scanProgressHub") && !ctx.Request.Path.StartsWithSegments("/health"), app => app.UseMiddleware()); // create a directory relative to the application's startup directory, and use it to store static files that are served at the /media route on the API string mediaRootDirectoryPathSetting = app.Configuration.GetValue("MediaSettings:RootDirectory") ?? string.Empty; @@ -165,6 +171,38 @@ public class Program app.MapHub("/scanProgressHub"); + // the liveness probe reports whether the process is running, while the readiness probe also verifies that the database is reachable + app.MapHealthChecks("/health/live", new HealthCheckOptions + { + Predicate = _ => false, + ResponseWriter = WriteHealthCheckResponseAsync + }); + app.MapHealthChecks("/health/ready", new HealthCheckOptions + { + Predicate = healthCheck => healthCheck.Tags.Contains("ready"), + ResponseWriter = WriteHealthCheckResponseAsync + }); + await app.RunAsync().ConfigureAwait(false); } + + /// + /// Writes the health report as a JSON response. + /// + /// The current HTTP context. + /// The health report to write. + private static async Task WriteHealthCheckResponseAsync(HttpContext httpContext, HealthReport healthReport) + { + httpContext.Response.ContentType = "application/json"; + await httpContext.Response.WriteAsJsonAsync(new + { + status = healthReport.Status.ToString(), + checks = healthReport.Entries.Select(entry => new + { + name = entry.Key, + status = entry.Value.Status.ToString(), + description = entry.Value.Description + }) + }); + } } diff --git a/src/Lumina.Presentation.Api/appsettings.json b/src/Lumina.Presentation.Api/appsettings.json index 85513e30..21276bf3 100644 --- a/src/Lumina.Presentation.Api/appsettings.json +++ b/src/Lumina.Presentation.Api/appsettings.json @@ -24,7 +24,7 @@ "Name": "Console", "Args": { "theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Literate, Serilog.Sinks.Console", - "outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}" + "outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {TraceId} {SpanId} {Message:lj}{NewLine}{Exception}" } }, { @@ -32,7 +32,7 @@ "Args": { "path": "%LOG_PATH%lumina_api_.log", "rollingInterval": "Day", - "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}", + "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {TraceId} {SpanId} {Message:lj}{NewLine}{Exception}", "retainedFileCountLimit": 7, "fileSizeLimitBytes": 10485760, "rollOnFileSizeLimit": true, @@ -45,7 +45,8 @@ "FromLogContext", "WithMachineName", "WithThreadId", - "WithEnvironmentName" + "WithEnvironmentName", + "WithSpan" ], "Properties": { "Application": "LuminaApi" @@ -57,11 +58,12 @@ "http://localhost:5012" ] }, - "Kestrel": { - "Endpoints": { - "Http": { - "Url": "http://localhost:5214" - } - } + "Telemetry": { + "Enabled": true, + "ConsoleExporterEnabled": false, + "Otlp": { + "Endpoint": "" + }, + "TraceSampleRatio": 0.25 // production default; override to 1.0 in the development configuration for full trace capture } } diff --git a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebTelemetryServices.cs b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebTelemetryServices.cs new file mode 100644 index 00000000..f6925745 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebTelemetryServices.cs @@ -0,0 +1,102 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Telemetry; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using OpenTelemetry; +using OpenTelemetry.Metrics; +using OpenTelemetry.Resources; +using OpenTelemetry.Trace; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Common.DependencyInjection; + +/// +/// Contains the OpenTelemetry services of the Presentation Web layer. +/// +[ExcludeFromCodeCoverage] +public static class PresentationWebTelemetryServices +{ + private const string SERVICE_NAME = "Lumina.Web"; + + /// + /// Registers the OpenTelemetry tracing and metrics pipelines into the dependency injection container. + /// + /// The service collection to add the services to. + /// Application configuration properties. + /// The hosting environment of the application. + /// The updated . + public static IServiceCollection AddPresentationWebTelemetryServices(this IServiceCollection services, IConfiguration configuration, IWebHostEnvironment environment) + { + bool isTelemetryEnabled = configuration.GetValue("Telemetry:Enabled") ?? true; + if (!isTelemetryEnabled) + return services; + + bool isConsoleExporterEnabled = configuration.GetValue("Telemetry:ConsoleExporterEnabled") ?? environment.IsDevelopment(); + string? otlpEndpoint = GetOtlpEndpoint(configuration); + double traceSampleRatio = configuration.GetValue("Telemetry:TraceSampleRatio") ?? 1.0; + string serviceVersion = typeof(Program).Assembly.GetName().Version?.ToString() ?? "unknown"; + + services.AddOpenTelemetry() + .ConfigureResource(resourceBuilder => resourceBuilder + .AddService(serviceName: SERVICE_NAME, serviceVersion: serviceVersion) + .AddEnvironmentVariableDetector() + .AddAttributes(new Dictionary + { + ["deployment.environment"] = environment.EnvironmentName + })) + .WithTracing(tracingBuilder => + { + tracingBuilder.SetSampler(CreateSampler(traceSampleRatio)); + tracingBuilder.AddSource(WebTelemetry.SOURCE_NAME); + tracingBuilder.AddAspNetCoreInstrumentation(); + // the HTTP client instrumentation emits spans and metrics for the calls to the API, and injects the W3C trace context + // into their headers, so that the API continues the same trace across the two separately deployed applications + tracingBuilder.AddHttpClientInstrumentation(); + if (isConsoleExporterEnabled) + tracingBuilder.AddConsoleExporter(); + if (otlpEndpoint is not null) + tracingBuilder.AddOtlpExporter(otlpExporterOptions => otlpExporterOptions.Endpoint = new Uri(otlpEndpoint)); + }) + .WithMetrics(metricsBuilder => + { + metricsBuilder.AddAspNetCoreInstrumentation(); + metricsBuilder.AddHttpClientInstrumentation(); + if (isConsoleExporterEnabled) + metricsBuilder.AddConsoleExporter(); + if (otlpEndpoint is not null) + metricsBuilder.AddOtlpExporter(otlpExporterOptions => otlpExporterOptions.Endpoint = new Uri(otlpEndpoint)); + }); + + return services; + } + + /// + /// Gets the OTLP exporter endpoint from configuration, falling back to the standard OTEL_EXPORTER_OTLP_ENDPOINT environment variable. + /// + /// Application configuration properties. + /// The OTLP endpoint, or when no endpoint is configured. + private static string? GetOtlpEndpoint(IConfiguration configuration) + { + string? endpoint = configuration.GetValue("Telemetry:Otlp:Endpoint"); + if (string.IsNullOrWhiteSpace(endpoint)) + endpoint = Environment.GetEnvironmentVariable("OTEL_EXPORTER_OTLP_ENDPOINT"); + return string.IsNullOrWhiteSpace(endpoint) ? null : endpoint; + } + + /// + /// Creates the trace sampler used by the Web application, sampling every trace by default and honoring the configured ratio for production traffic. + /// + /// The ratio of traces to sample, in the range of zero to one. + /// The configured trace sampler. + private static Sampler CreateSampler(double traceSampleRatio) + { + return traceSampleRatio < 1.0 + ? new ParentBasedSampler(new TraceIdRatioBasedSampler(traceSampleRatio)) + : new AlwaysOnSampler(); + } +} diff --git a/src/Lumina.Presentation.Web/Common/HealthChecks/ApiReachabilityHealthCheck.cs b/src/Lumina.Presentation.Web/Common/HealthChecks/ApiReachabilityHealthCheck.cs new file mode 100644 index 00000000..496e1493 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/HealthChecks/ApiReachabilityHealthCheck.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Configuration; +using Microsoft.Extensions.Diagnostics.HealthChecks; +using Microsoft.Extensions.Options; +using System; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Common.HealthChecks; + +/// +/// Health check that verifies the remote API is reachable. +/// +public class ApiReachabilityHealthCheck : IHealthCheck +{ + private readonly HttpClient _httpClient; + private readonly ServerConfigurationDto _serverConfiguration; + + /// + /// Initializes a new instance of the class. + /// + /// Injected factory for creating HTTP clients. + /// Injected server configuration application settings. + public ApiReachabilityHealthCheck(IHttpClientFactory httpClientFactory, IOptionsSnapshot serverConfigurationOptions) + { + _httpClient = httpClientFactory.CreateClient(); + _serverConfiguration = serverConfigurationOptions.Value; + } + + /// + /// Checks whether the remote API is reachable by probing its readiness endpoint. + /// + /// The health check context. + /// Token to monitor for cancellation requests. + /// A task that represents the asynchronous operation, containing the health check result. + public virtual async Task CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken) + { + string healthUrl = $"{_serverConfiguration.BaseAddress}:{_serverConfiguration.Port}/health/ready"; + using CancellationTokenSource timeoutCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeoutCancellationTokenSource.CancelAfter(TimeSpan.FromSeconds(5)); + try + { + using HttpResponseMessage response = await _httpClient.GetAsync(healthUrl, timeoutCancellationTokenSource.Token).ConfigureAwait(false); + return response.IsSuccessStatusCode + ? HealthCheckResult.Healthy() + : HealthCheckResult.Unhealthy($"The API returned status {(int)response.StatusCode}."); + } + catch (Exception exception) + { + return HealthCheckResult.Unhealthy("The API is not reachable.", exception); + } + } +} diff --git a/src/Lumina.Presentation.Web/Common/Telemetry/WebTelemetry.cs b/src/Lumina.Presentation.Web/Common/Telemetry/WebTelemetry.cs new file mode 100644 index 00000000..0fc6329e --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Telemetry/WebTelemetry.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Telemetry; + +/// +/// Central registry of the used by the Presentation Web layer to emit traces. +/// +public static class WebTelemetry +{ + /// + /// The source name shared by the of the Presentation Web layer. + /// + public const string SOURCE_NAME = "Lumina.Web"; + + /// + /// The source of the traces emitted by the Presentation Web layer. + /// + public static ActivitySource ActivitySource { get; } = new(SOURCE_NAME); +} diff --git a/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj b/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj index 6b86fafb..ccdd2176 100644 --- a/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj +++ b/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj @@ -25,10 +25,17 @@ + + + + + + + diff --git a/src/Lumina.Presentation.Web/Program.cs b/src/Lumina.Presentation.Web/Program.cs index c1e4d5bf..c6d9dc6d 100644 --- a/src/Lumina.Presentation.Web/Program.cs +++ b/src/Lumina.Presentation.Web/Program.cs @@ -1,11 +1,14 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; using Lumina.Presentation.Web.Common.DependencyInjection; +using Lumina.Presentation.Web.Common.HealthChecks; using Lumina.Presentation.Web.Common.Utilities; using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Primitives; using Scalar.AspNetCore; @@ -35,6 +38,9 @@ public class Program builder.Services.BindConfiguration(builder.Configuration); builder.Services.AddPresentationWebLayerServices(); + builder.Services.AddPresentationWebTelemetryServices(builder.Configuration, builder.Environment); + builder.Services.AddHealthChecks() + .AddCheck("api", HealthStatus.Unhealthy, ["ready"]); // determine log path based on environment string logPath; @@ -122,6 +128,11 @@ public class Program .WithDotNetFlag(true); }); + // liveness and readiness probes, probed by container orchestrators and load balancers; the readiness probe also + // verifies that the API is reachable, so the web application is only reported ready when it can actually serve requests + app.MapHealthChecks("/health/live", new HealthCheckOptions { Predicate = _ => false }); + app.MapHealthChecks("/health/ready", new HealthCheckOptions { Predicate = healthCheck => healthCheck.Tags.Contains("ready") }); + await app.RunAsync(); } } diff --git a/src/Lumina.Presentation.Web/appsettings.json b/src/Lumina.Presentation.Web/appsettings.json index 73c0a7f4..e7297334 100644 --- a/src/Lumina.Presentation.Web/appsettings.json +++ b/src/Lumina.Presentation.Web/appsettings.json @@ -20,7 +20,7 @@ "Name": "Console", "Args": { "theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Literate, Serilog.Sinks.Console", - "outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}" + "outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {TraceId} {SpanId} {Message:lj}{NewLine}{Exception}" } }, { @@ -28,7 +28,7 @@ "Args": { "path": "%LOG_PATH%lumina_web_.log", "rollingInterval": "Day", - "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}", + "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {TraceId} {SpanId} {Message:lj}{NewLine}{Exception}", "retainedFileCountLimit": 7, "fileSizeLimitBytes": 10485760, "rollOnFileSizeLimit": true, @@ -42,7 +42,8 @@ "WithMachineName", "WithThreadId", "WithEnvironmentName", - "WithRequestId" + "WithRequestId", + "WithSpan" ], "Properties": { "Application": "LuminaWeb" @@ -54,11 +55,12 @@ "BaseAddress": "http://localhost", "Port": 5214 }, - "Kestrel": { - "Endpoints": { - "Http": { - "Url": "http://localhost:5012" - } - } + "Telemetry": { + "Enabled": true, + "ConsoleExporterEnabled": false, + "Otlp": { + "Endpoint": "" + }, + "TraceSampleRatio": 0.25 // production default; override to 1.0 in the development configuration for full trace capture } } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Health/FailingDatabaseApiFactory.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Health/FailingDatabaseApiFactory.cs new file mode 100644 index 00000000..6b3bc6f8 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Health/FailingDatabaseApiFactory.cs @@ -0,0 +1,32 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Api.Common.HealthChecks; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Health; + +/// +/// Factory whose database health check always reports an unhealthy state. +/// +[ExcludeFromCodeCoverage] +public class FailingDatabaseApiFactory : LuminaApiFactory +{ + /// + /// Configures the web host, replacing the database health check with one that always fails. + /// + /// The web host builder to configure. + protected override void ConfigureWebHost(IWebHostBuilder builder) + { + base.ConfigureWebHost(builder); + builder.ConfigureServices(services => + { + // the health check resolves DatabaseHealthCheck from DI when it runs, so replacing its registration with a failing subclass makes /health/ready report Unhealthy + services.RemoveAll(); + services.AddScoped(); + }); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Health/FailingDatabaseHealthCheck.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Health/FailingDatabaseHealthCheck.cs new file mode 100644 index 00000000..2d6a625c --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Health/FailingDatabaseHealthCheck.cs @@ -0,0 +1,33 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.DataAccess.Core.UoW; +using Lumina.Presentation.Api.Common.HealthChecks; +using Microsoft.Extensions.Diagnostics.HealthChecks; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Health; + +/// +/// Database health check that always reports an unhealthy state. +/// +[ExcludeFromCodeCoverage] +internal sealed class FailingDatabaseHealthCheck : DatabaseHealthCheck +{ + /// + /// Initializes a new instance of the class. + /// + /// Injected database context. + public FailingDatabaseHealthCheck(LuminaDbContext dbContext) : base(dbContext) + { + } + + /// + /// Reports an unhealthy state without probing the database. + /// + public override Task CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken) + { + return Task.FromResult(HealthCheckResult.Unhealthy("database unavailable")); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Health/HealthEndpointFailureTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Health/HealthEndpointFailureTests.cs new file mode 100644 index 00000000..e99d50b3 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Health/HealthEndpointFailureTests.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Health; + +/// +/// Contains integration tests for the /health/ready probe route when the database is unreachable. +/// +[ExcludeFromCodeCoverage] +public class HealthEndpointFailureTests : IClassFixture +{ + private readonly HttpClient _client; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory with a failing database health check. + public HealthEndpointFailureTests(FailingDatabaseApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task HealthReady_WhenDatabaseIsUnreachable_ShouldReturnServiceUnavailable() + { + // Act + HttpResponseMessage response = await _client.GetAsync("/health/ready"); + + // Assert + Assert.Equal(HttpStatusCode.ServiceUnavailable, response.StatusCode); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Health/HealthEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Health/HealthEndpointTests.cs new file mode 100644 index 00000000..9fe5c4dd --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Health/HealthEndpointTests.cs @@ -0,0 +1,68 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Health; + +/// +/// Contains integration tests for the /health/live and /health/ready probe routes. +/// +[ExcludeFromCodeCoverage] +public class HealthEndpointTests : IClassFixture +{ + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public HealthEndpointTests(LuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task HealthLive_WhenCalled_ShouldReturnOk() + { + // Act + HttpResponseMessage response = await _client.GetAsync("/health/live"); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact] + public async Task HealthReady_WhenDatabaseIsReachable_ShouldReturnHealthyReport() + { + // Act + HttpResponseMessage response = await _client.GetAsync("/health/ready"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + HealthReportDto report = JsonSerializer.Deserialize(content, _jsonOptions)!; + Assert.Equal("Healthy", report.Status); + HealthCheckReportDto databaseCheck = Assert.Single(report.Checks, check => check.Name == "database"); + Assert.Equal("Healthy", databaseCheck.Status); + } + + /// + /// Deserialized shape of the health report JSON written by the API. + /// + private sealed record HealthReportDto(string Status, List Checks); + + /// + /// Deserialized shape of a single health check entry within the health report. + /// + private sealed record HealthCheckReportDto(string Name, string Status, string? Description); +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Common/Setup/HealthyApiReachabilityHealthCheck.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Common/Setup/HealthyApiReachabilityHealthCheck.cs new file mode 100644 index 00000000..f0ee4f3c --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Common/Setup/HealthyApiReachabilityHealthCheck.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Configuration; +using Lumina.Presentation.Web.Common.HealthChecks; +using Microsoft.Extensions.Diagnostics.HealthChecks; +using Microsoft.Extensions.Options; +using System.Diagnostics.CodeAnalysis; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Common.Setup; + +/// +/// API reachability health check that always reports a healthy state. +/// +[ExcludeFromCodeCoverage] +internal sealed class HealthyApiReachabilityHealthCheck : ApiReachabilityHealthCheck +{ + /// + /// Initializes a new instance of the class. + /// + /// Injected factory for creating HTTP clients. + /// Injected server configuration application settings. + public HealthyApiReachabilityHealthCheck(IHttpClientFactory httpClientFactory, IOptionsSnapshot serverConfigurationOptions) + : base(httpClientFactory, serverConfigurationOptions) + { + } + + /// + /// Reports a healthy state without probing the API. + /// + public override Task CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken) + { + return Task.FromResult(HealthCheckResult.Healthy()); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Common/Setup/LuminaWebFactory.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Common/Setup/LuminaWebFactory.cs index 0ade61d2..e36b6f1e 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Common/Setup/LuminaWebFactory.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Common/Setup/LuminaWebFactory.cs @@ -1,11 +1,13 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Web; using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.HealthChecks; using Lumina.Presentation.Web.Fixtures.Common.Api; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -58,6 +60,11 @@ public class LuminaWebFactory : WebApplicationFactory, IDisposable foreach (ServiceDescriptor descriptor in apiClientDescriptors) services.Remove(descriptor); services.AddSingleton(ApiClientStub); + + // the API reachability health check resolves ApiReachabilityHealthCheck from DI when it runs; replace its + // registration with a healthy subclass, since no real API exists during these tests + services.RemoveAll(); + services.AddScoped(); }); } } diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Health/FailingApiHealthFactory.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Health/FailingApiHealthFactory.cs new file mode 100644 index 00000000..67403fea --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Health/FailingApiHealthFactory.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.HealthChecks; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Health; + +/// +/// Factory whose API reachability health check always reports an unhealthy state. +/// +[ExcludeFromCodeCoverage] +public class FailingApiHealthFactory : LuminaWebFactory +{ + /// + /// Configures the web host, replacing the API reachability health check with one that always fails. + /// + /// The web host builder to configure. + protected override void ConfigureWebHost(IWebHostBuilder builder) + { + base.ConfigureWebHost(builder); + builder.ConfigureServices(services => + { + services.RemoveAll(); + services.AddScoped(); + }); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Health/HealthEndpointFailureTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Health/HealthEndpointFailureTests.cs new file mode 100644 index 00000000..f474e79b --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Health/HealthEndpointFailureTests.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Health; + +/// +/// Contains integration tests for the /health/ready probe route when the API is unreachable. +/// +[ExcludeFromCodeCoverage] +public class HealthEndpointFailureTests : IClassFixture +{ + private readonly FailingApiHealthFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory with a failing API reachability check. + public HealthEndpointFailureTests(FailingApiHealthFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task HealthReady_WhenApiIsUnreachable_ShouldReturnServiceUnavailable() + { + // Arrange + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/health/ready"); + + // Assert + Assert.Equal(HttpStatusCode.ServiceUnavailable, response.StatusCode); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Health/HealthEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Health/HealthEndpointTests.cs new file mode 100644 index 00000000..33c27851 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Health/HealthEndpointTests.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Health; + +/// +/// Contains integration tests for the /health/live and /health/ready probe routes. +/// +[ExcludeFromCodeCoverage] +public class HealthEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public HealthEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task HealthLive_WhenCalled_ShouldReturnOk() + { + // Arrange + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/health/live"); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact] + public async Task HealthReady_WhenApiIsReachable_ShouldReturnHealthy() + { + // Arrange + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/health/ready"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Contains("Healthy", content, System.StringComparison.OrdinalIgnoreCase); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Health/UnhealthyApiReachabilityHealthCheck.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Health/UnhealthyApiReachabilityHealthCheck.cs new file mode 100644 index 00000000..e66af15d --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Health/UnhealthyApiReachabilityHealthCheck.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Configuration; +using Lumina.Presentation.Web.Common.HealthChecks; +using Microsoft.Extensions.Diagnostics.HealthChecks; +using Microsoft.Extensions.Options; +using System.Diagnostics.CodeAnalysis; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Health; + +/// +/// API reachability health check that always reports an unhealthy state. +/// +[ExcludeFromCodeCoverage] +internal sealed class UnhealthyApiReachabilityHealthCheck : ApiReachabilityHealthCheck +{ + /// + /// Initializes a new instance of the class. + /// + /// Injected factory for creating HTTP clients. + /// Injected server configuration application settings. + public UnhealthyApiReachabilityHealthCheck(IHttpClientFactory httpClientFactory, IOptionsSnapshot serverConfigurationOptions) + : base(httpClientFactory, serverConfigurationOptions) + { + } + + /// + /// Reports an unhealthy state without probing the API. + /// + public override Task CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken) + { + return Task.FromResult(HealthCheckResult.Unhealthy("api unreachable")); + } +}