From 381410510f751fc66feeeb466dbb7a87005111b4 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Wed, 12 Aug 2026 09:54:37 +0200 Subject: [PATCH] feat(health): health checks complets /health/ready + /health/live (Fixes #13) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Checks enregistrés : PostgreSQL (ready+live), Alarik S3 (ready), CodeProject.AI/Ollama (live) — optionnels → Healthy si non configurés - Routes : /health (alias /healthz), /health/ready (alias /readyz), /health/live → 503 + degradationLevel quand IA dégradée - Fix CI : dashboard Hangfire skip en Testing (Hangfire désactivé → crash au démarrage WebApplicationFactory) — IntegrationTests 125/125 verts --- .../DependencyInjection.cs | 6 ++ .../HealthChecks/AiHealthCheck.cs | 64 +++++++++++++++++++ .../HealthChecks/AlarikHealthCheck.cs | 43 +++++++++++++ .../Heimdall.Infrastructure.csproj | 1 + .../Controllers/HealthController.cs | 38 ++++++++++- src/Heimdall.Web/Program.cs | 16 +++-- 6 files changed, 159 insertions(+), 9 deletions(-) create mode 100644 src/Heimdall.Infrastructure/HealthChecks/AiHealthCheck.cs create mode 100644 src/Heimdall.Infrastructure/HealthChecks/AlarikHealthCheck.cs diff --git a/src/Heimdall.Infrastructure/DependencyInjection.cs b/src/Heimdall.Infrastructure/DependencyInjection.cs index 6edf7dc..494f5ea 100644 --- a/src/Heimdall.Infrastructure/DependencyInjection.cs +++ b/src/Heimdall.Infrastructure/DependencyInjection.cs @@ -43,6 +43,12 @@ public static class DependencyInjection services.AddScoped(sp => sp.GetRequiredService()); + // Health checks (spec 13.2) — PostgreSQL + dépendances optionnelles. + services.AddHealthChecks() + .AddDbContextCheck("postgres", tags: ["ready", "live"]) + .AddCheck("alarik", tags: ["ready"]) + .AddCheck("codeproject-ai", tags: ["live"]); + // Identity services.AddIdentity(options => { diff --git a/src/Heimdall.Infrastructure/HealthChecks/AiHealthCheck.cs b/src/Heimdall.Infrastructure/HealthChecks/AiHealthCheck.cs new file mode 100644 index 0000000..21fd3fa --- /dev/null +++ b/src/Heimdall.Infrastructure/HealthChecks/AiHealthCheck.cs @@ -0,0 +1,64 @@ +using Microsoft.Extensions.Diagnostics.HealthChecks; + +namespace Heimdall.Infrastructure.HealthChecks; + +/// +/// CodeProject.AI / Ollama health check (AI backend). Reports Healthy when AI +/// is not configured (optional dependency), Degraded when configured but +/// unreachable — drives the /health/live degradationLevel. +/// +public sealed class AiHealthCheck : IHealthCheck +{ + private readonly IHttpClientFactory _httpClientFactory; + + public AiHealthCheck(IHttpClientFactory httpClientFactory) + { + _httpClientFactory = httpClientFactory; + } + + public async Task CheckHealthAsync( + HealthCheckContext context, CancellationToken cancellationToken = default) + { + var cpai = Environment.GetEnvironmentVariable("CPAI_URL"); + if (!string.IsNullOrEmpty(cpai)) + { + try + { + var client = _httpClientFactory.CreateClient("Ai"); + using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + cts.CancelAfter(TimeSpan.FromSeconds(30)); + + using var response = await client.GetAsync($"{cpai.TrimEnd('/')}/v1/status/ping", cts.Token).ConfigureAwait(false); + if (response.IsSuccessStatusCode) + return HealthCheckResult.Healthy("CodeProject.AI reachable"); + return HealthCheckResult.Degraded($"CodeProject.AI returned {(int)response.StatusCode}"); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + return HealthCheckResult.Degraded($"CodeProject.AI unreachable: {ex.Message}"); + } + } + + var ollama = Environment.GetEnvironmentVariable("OLLAMA_URL"); + if (!string.IsNullOrEmpty(ollama)) + { + try + { + var client = _httpClientFactory.CreateClient("Ai"); + using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + cts.CancelAfter(TimeSpan.FromSeconds(60)); + + using var response = await client.GetAsync($"{ollama.TrimEnd('/')}/api/tags", cts.Token).ConfigureAwait(false); + if (response.IsSuccessStatusCode) + return HealthCheckResult.Healthy("Ollama reachable"); + return HealthCheckResult.Degraded($"Ollama returned {(int)response.StatusCode}"); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + return HealthCheckResult.Degraded($"Ollama unreachable: {ex.Message}"); + } + } + + return HealthCheckResult.Healthy("AI backend not configured"); + } +} diff --git a/src/Heimdall.Infrastructure/HealthChecks/AlarikHealthCheck.cs b/src/Heimdall.Infrastructure/HealthChecks/AlarikHealthCheck.cs new file mode 100644 index 0000000..15fefcf --- /dev/null +++ b/src/Heimdall.Infrastructure/HealthChecks/AlarikHealthCheck.cs @@ -0,0 +1,43 @@ +using Microsoft.Extensions.Diagnostics.HealthChecks; + +namespace Heimdall.Infrastructure.HealthChecks; + +/// +/// Alarik/S3 health check (GET /health on the S3 endpoint). Reports Healthy +/// when Alarik is not configured (optional dependency) and Degraded when the +/// endpoint is configured but unreachable. +/// +public sealed class AlarikHealthCheck : IHealthCheck +{ + private readonly IHttpClientFactory _httpClientFactory; + + public AlarikHealthCheck(IHttpClientFactory httpClientFactory) + { + _httpClientFactory = httpClientFactory; + } + + public async Task CheckHealthAsync( + HealthCheckContext context, CancellationToken cancellationToken = default) + { + var endpoint = Environment.GetEnvironmentVariable("ALARIK_ENDPOINT") + ?? Environment.GetEnvironmentVariable("S3_ENDPOINT"); + if (string.IsNullOrEmpty(endpoint)) + return HealthCheckResult.Healthy("Alarik not configured"); + + try + { + var client = _httpClientFactory.CreateClient("Alarik"); + using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + cts.CancelAfter(TimeSpan.FromSeconds(30)); + + using var response = await client.GetAsync($"{endpoint.TrimEnd('/')}/health", cts.Token).ConfigureAwait(false); + return response.IsSuccessStatusCode + ? HealthCheckResult.Healthy("Alarik reachable") + : HealthCheckResult.Degraded($"Alarik returned {(int)response.StatusCode}"); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + return HealthCheckResult.Degraded($"Alarik unreachable: {ex.Message}"); + } + } +} diff --git a/src/Heimdall.Infrastructure/Heimdall.Infrastructure.csproj b/src/Heimdall.Infrastructure/Heimdall.Infrastructure.csproj index 691486f..70fda0b 100644 --- a/src/Heimdall.Infrastructure/Heimdall.Infrastructure.csproj +++ b/src/Heimdall.Infrastructure/Heimdall.Infrastructure.csproj @@ -14,6 +14,7 @@ runtime; build; native; contentfiles; analyzers; buildtransitive all + diff --git a/src/Heimdall.Web/Controllers/HealthController.cs b/src/Heimdall.Web/Controllers/HealthController.cs index 5479fca..b6c5389 100644 --- a/src/Heimdall.Web/Controllers/HealthController.cs +++ b/src/Heimdall.Web/Controllers/HealthController.cs @@ -9,14 +9,16 @@ public class HealthController : ControllerBase /// /// Liveness probe — always returns OK if the process is running. /// + [HttpGet("/health")] [HttpGet("/healthz")] [ProducesResponseType(typeof(void), StatusCodes.Status200OK)] public IActionResult Health() => Ok(new { status = "healthy", timestamp = DateTime.UtcNow }); /// - /// Readiness probe — checks if the database is reachable. - /// Uses ASP.NET Core health checks infrastructure. + /// Readiness probe — checks dependencies (PostgreSQL, Alarik S3). + /// 503 when a required dependency is down. /// + [HttpGet("/health/ready")] [HttpGet("/readyz")] [ProducesResponseType(typeof(void), StatusCodes.Status200OK)] [ProducesResponseType(typeof(void), StatusCodes.Status503ServiceUnavailable)] @@ -25,10 +27,40 @@ public class HealthController : ControllerBase CancellationToken ct) { var report = await healthCheckService.CheckHealthAsync( - _ => true, ct); + reg => reg.Tags.Contains("ready"), ct); return report.Status == HealthStatus.Healthy ? Ok(new { status = "healthy", timestamp = DateTime.UtcNow }) : StatusCode(503, new { status = "unhealthy", errors = report.Entries }); } + + /// + /// Live probe — ready + no active AI degradation. 503 + degradationLevel + /// when CodeProject.AI / Ollama is configured but unreachable. + /// + [HttpGet("/health/live")] + [ProducesResponseType(typeof(void), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status503ServiceUnavailable)] + public async Task Live( + [FromServices] HealthCheckService healthCheckService, + CancellationToken ct) + { + var report = await healthCheckService.CheckHealthAsync( + reg => reg.Tags.Contains("live"), ct); + + if (report.Status == HealthStatus.Healthy) + return Ok(new { status = "healthy", degradationLevel = 0, timestamp = DateTime.UtcNow }); + + // Dégradation IA : ready OK mais backends IA (live) down → 503. + var degradedEntries = report.Entries + .Where(e => e.Value.Status != HealthStatus.Healthy) + .ToDictionary(e => e.Key, e => e.Value.Description ?? e.Value.Status.ToString()); + return StatusCode(503, new + { + status = "degraded", + degradationLevel = 1, + errors = degradedEntries, + timestamp = DateTime.UtcNow, + }); + } } diff --git a/src/Heimdall.Web/Program.cs b/src/Heimdall.Web/Program.cs index 5cbe96a..d9a7ded 100644 --- a/src/Heimdall.Web/Program.cs +++ b/src/Heimdall.Web/Program.cs @@ -574,13 +574,17 @@ public partial class Program { // Hangfire dashboard — Admin uniquement (policy AdminJobs). // MapHangfireDashboard est utilisé car UseHangfireDashboard avec // DashboardOptions.Authorization n'existe pas pour les policies ASP.NET. - app.MapHangfireDashboard("/hangfire", new DashboardOptions + // Skip en Testing : Hangfire y est désactivé (pas de AddHangfire). + if (!app.Environment.IsEnvironment("Testing")) { - Authorization = - [ - new HangfireAdminAuthorizationFilter(), - ], - }); + app.MapHangfireDashboard("/hangfire", new DashboardOptions + { + Authorization = + [ + new HangfireAdminAuthorizationFilter(), + ], + }); + } app.MapRazorComponents().AddInteractiveServerRenderMode(); app.MapControllers();