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