From 2d2e5bc211c6e62c3b7b0352fa7a70c9dae7fb23 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sat, 24 Oct 2026 21:47:40 +0200 Subject: [PATCH] fix(health): check the active storage provider --- .../DependencyInjection.cs | 4 +- .../HealthChecks/AlarikHealthCheck.cs | 43 ------------------ .../HealthChecks/StorageHealthCheck.cs | 45 +++++++++++++++++++ .../Storage/AlarikStorageProvider.cs | 12 ++++- .../Storage/LocalStorageProvider.cs | 16 +++++-- .../Controllers/HealthController.cs | 2 +- todo.md | 2 +- 7 files changed, 73 insertions(+), 51 deletions(-) delete mode 100644 src/Heimdall.Infrastructure/HealthChecks/AlarikHealthCheck.cs create mode 100644 src/Heimdall.Infrastructure/HealthChecks/StorageHealthCheck.cs diff --git a/src/Heimdall.Infrastructure/DependencyInjection.cs b/src/Heimdall.Infrastructure/DependencyInjection.cs index 51ea8fa..7338496 100644 --- a/src/Heimdall.Infrastructure/DependencyInjection.cs +++ b/src/Heimdall.Infrastructure/DependencyInjection.cs @@ -55,7 +55,9 @@ public static class DependencyInjection // Health checks (spec 13.2) — PostgreSQL + dépendances optionnelles. services.AddHealthChecks() .AddDbContextCheck("postgres", tags: ["ready", "live"]) - .AddCheck("alarik", tags: ["ready"]) + .AddCheck( + "storage", failureStatus: Microsoft.Extensions.Diagnostics.HealthChecks.HealthStatus.Degraded, + tags: ["ready"], timeout: TimeSpan.FromSeconds(8)) .AddCheck("codeproject-ai", tags: ["live"]); // Identity diff --git a/src/Heimdall.Infrastructure/HealthChecks/AlarikHealthCheck.cs b/src/Heimdall.Infrastructure/HealthChecks/AlarikHealthCheck.cs deleted file mode 100644 index 15fefcf..0000000 --- a/src/Heimdall.Infrastructure/HealthChecks/AlarikHealthCheck.cs +++ /dev/null @@ -1,43 +0,0 @@ -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/HealthChecks/StorageHealthCheck.cs b/src/Heimdall.Infrastructure/HealthChecks/StorageHealthCheck.cs new file mode 100644 index 0000000..76c366e --- /dev/null +++ b/src/Heimdall.Infrastructure/HealthChecks/StorageHealthCheck.cs @@ -0,0 +1,45 @@ +using Heimdall.Infrastructure.Storage; +using Microsoft.Extensions.Diagnostics.HealthChecks; + +namespace Heimdall.Infrastructure.HealthChecks; + +/// Checks the storage provider currently selected in Heimdall settings. +public sealed class StorageHealthCheck : IHealthCheck +{ + private static readonly TimeSpan ProbeTimeout = TimeSpan.FromSeconds(5); + private readonly StorageProviderFactory _storage; + + public StorageHealthCheck(StorageProviderFactory storage) + { + _storage = storage; + } + + public async Task CheckHealthAsync( + HealthCheckContext context, CancellationToken cancellationToken = default) + { + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeout.CancelAfter(ProbeTimeout); + + try + { + var isHealthy = await _storage.HealthCheckAsync(timeout.Token).ConfigureAwait(false); + return isHealthy + ? HealthCheckResult.Healthy("Active storage provider is available") + : HealthCheckResult.Degraded("Active storage provider is unavailable or misconfigured"); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + throw; + } + catch (OperationCanceledException) + { + return HealthCheckResult.Degraded("Active storage health probe timed out"); + } + catch (Exception) + { + // Avoid returning configuration, endpoint, or credential details in + // the public readiness response. + return HealthCheckResult.Degraded("Active storage provider is unavailable or misconfigured"); + } + } +} diff --git a/src/Heimdall.Infrastructure/Storage/AlarikStorageProvider.cs b/src/Heimdall.Infrastructure/Storage/AlarikStorageProvider.cs index f2153ba..73021e7 100644 --- a/src/Heimdall.Infrastructure/Storage/AlarikStorageProvider.cs +++ b/src/Heimdall.Infrastructure/Storage/AlarikStorageProvider.cs @@ -194,12 +194,20 @@ public sealed class AlarikStorageProvider : IStorageProvider, IDisposable return false; try { - await _client.ListBucketsAsync(ct).ConfigureAwait(false); + await _client.ListObjectsV2Async(new ListObjectsV2Request + { + BucketName = _bucket, + MaxKeys = 1, + }, ct).ConfigureAwait(false); return true; } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + throw; + } catch (Exception ex) { - _logger.LogWarning(ex, "Alarik/S3 health check failed"); + _logger.LogWarning(ex, "S3 storage bucket health check failed"); return false; } } diff --git a/src/Heimdall.Infrastructure/Storage/LocalStorageProvider.cs b/src/Heimdall.Infrastructure/Storage/LocalStorageProvider.cs index 2310a9e..23f7a53 100644 --- a/src/Heimdall.Infrastructure/Storage/LocalStorageProvider.cs +++ b/src/Heimdall.Infrastructure/Storage/LocalStorageProvider.cs @@ -195,19 +195,29 @@ public sealed class LocalStorageProvider : IStorageProvider sorted.Length > pageSize ? objects[^1].Key : null)); } - public Task HealthCheckAsync(CancellationToken ct = default) + public async Task HealthCheckAsync(CancellationToken ct = default) { try { EnsureNoLinks(_root); Directory.CreateDirectory(_root); EnsureNoLinks(_root); - return Task.FromResult(true); + + var probePath = Path.Combine(_root, $".heimdall-health-{Guid.NewGuid():N}.tmp"); + await using var probe = new FileStream(probePath, FileMode.CreateNew, FileAccess.Write, + FileShare.None, bufferSize: 1, FileOptions.Asynchronous | FileOptions.DeleteOnClose); + await probe.WriteAsync(new byte[] { 0 }.AsMemory(), ct).ConfigureAwait(false); + await probe.FlushAsync(ct).ConfigureAwait(false); + return true; + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + throw; } catch (Exception ex) { _logger.LogWarning(ex, "Local storage health check failed"); - return Task.FromResult(false); + return false; } } } diff --git a/src/Heimdall.Web/Controllers/HealthController.cs b/src/Heimdall.Web/Controllers/HealthController.cs index 1d82549..546d6c9 100644 --- a/src/Heimdall.Web/Controllers/HealthController.cs +++ b/src/Heimdall.Web/Controllers/HealthController.cs @@ -16,7 +16,7 @@ public class HealthController : ControllerBase public IActionResult Health() => Ok(new { status = "healthy", timestamp = DateTime.UtcNow }); /// - /// Readiness probe — checks dependencies (PostgreSQL, Alarik S3). + /// Readiness probe — checks dependencies (PostgreSQL and active object storage provider). /// 503 when a required dependency is down. /// [HttpGet("/health/ready")] diff --git a/todo.md b/todo.md index 7368f7a..1c77e88 100644 --- a/todo.md +++ b/todo.md @@ -45,7 +45,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **Localisation #142** Extraire tous les textes UI, erreurs, notifications et emails ; persister FR/EN par utilisateur, basculer sans rechargement, garder français par défaut et vérifier les clés des deux ressources. - [ ] **Métriques #14** Les endpoints Prometheus `/metrics` Web et Agent sont mappés. La PR #68 ajoute et valide `heimdall.signalr.connections_by_hub` sur les cinq hubs Web. La jauge de viewers existe, mais aucun producteur WebRTC n'existe avant FEAT-01. Restent la validation de scraping sur un déploiement et l'évolution réelle des mesures. - [x] Ajouter `.agents/skills/secure-env-secrets/SKILL.md` : procédures pour lire/écrire les secrets fournis par l'utilisateur dans l'environnement local, avec stockage persistant optionnel hors dépôt, permissions utilisateur uniquement et sans exposer la valeur. Le skill ne configure pas les secrets des workflows distants. -- [ ] Vérifier readiness et alertes pour modèle absent, file pleine, backlog, disque, jobs bloqués, perte de configuration et échec de livraison. +- [ ] Vérifier readiness et alertes pour modèle absent, file pleine, backlog, disque, jobs bloqués, perte de configuration et échec de livraison. Le contrôle stockage est aligné sur le fournisseur actif (settings DB/env), avec probe d’écriture locale, probe du bucket S3 sélectionné et timeout borné ; les scénarios réels de panne restent à valider. - [ ] Actualiser les guides après chaque changement d'infrastructure, routes/API et statut produit ; distinguer implémenté, validé, partiel et prévu. Vérifier une installation depuis la documentation. ## Corrections déjà livrées à préserver