feat(health): health checks complets /health/ready + /health/live (Fixes #13)
- 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
This commit is contained in:
1 parent
e3d14eec04
commit
381410510f
6 files changed
+159
-9
No files matched your search
@@ -43,6 +43,12 @@ public static class DependencyInjection
|
||||
|
||||
services.AddScoped<IApplicationDbContext>(sp => sp.GetRequiredService<AppDbContext>());
|
||||
|
||||
// Health checks (spec 13.2) — PostgreSQL + dépendances optionnelles.
|
||||
services.AddHealthChecks()
|
||||
.AddDbContextCheck<AppDbContext>("postgres", tags: ["ready", "live"])
|
||||
.AddCheck<Infrastructure.HealthChecks.AlarikHealthCheck>("alarik", tags: ["ready"])
|
||||
.AddCheck<Infrastructure.HealthChecks.AiHealthCheck>("codeproject-ai", tags: ["live"]);
|
||||
|
||||
// Identity
|
||||
services.AddIdentity<AppUser, AppRole>(options =>
|
||||
{
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
using Microsoft.Extensions.Diagnostics.HealthChecks;
|
||||
|
||||
namespace Heimdall.Infrastructure.HealthChecks;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public sealed class AiHealthCheck : IHealthCheck
|
||||
{
|
||||
private readonly IHttpClientFactory _httpClientFactory;
|
||||
|
||||
public AiHealthCheck(IHttpClientFactory httpClientFactory)
|
||||
{
|
||||
_httpClientFactory = httpClientFactory;
|
||||
}
|
||||
|
||||
public async Task<HealthCheckResult> 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");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
using Microsoft.Extensions.Diagnostics.HealthChecks;
|
||||
|
||||
namespace Heimdall.Infrastructure.HealthChecks;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public sealed class AlarikHealthCheck : IHealthCheck
|
||||
{
|
||||
private readonly IHttpClientFactory _httpClientFactory;
|
||||
|
||||
public AlarikHealthCheck(IHttpClientFactory httpClientFactory)
|
||||
{
|
||||
_httpClientFactory = httpClientFactory;
|
||||
}
|
||||
|
||||
public async Task<HealthCheckResult> 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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore" Version="10.0.8" />
|
||||
|
||||
<PackageReference Include="Microsoft.AspNetCore.DataProtection.Extensions" Version="10.0.8" />
|
||||
<PackageReference Include="Hangfire.PostgreSql" Version="1.20.10" />
|
||||
|
||||
@@ -9,14 +9,16 @@ public class HealthController : ControllerBase
|
||||
/// <summary>
|
||||
/// Liveness probe — always returns OK if the process is running.
|
||||
/// </summary>
|
||||
[HttpGet("/health")]
|
||||
[HttpGet("/healthz")]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status200OK)]
|
||||
public IActionResult Health() => Ok(new { status = "healthy", timestamp = DateTime.UtcNow });
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[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 });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Live probe — ready + no active AI degradation. 503 + degradationLevel
|
||||
/// when CodeProject.AI / Ollama is configured but unreachable.
|
||||
/// </summary>
|
||||
[HttpGet("/health/live")]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status503ServiceUnavailable)]
|
||||
public async Task<IActionResult> 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,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -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<App>().AddInteractiveServerRenderMode();
|
||||
app.MapControllers();
|
||||
|
||||
Reference in new issue
Block a user