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}"); } } }