| | | 1 | | using ArturRios.Data.Relational.Core.Interfaces; |
| | | 2 | | using ArturRios.Heimdall.Domain.Entities; |
| | | 3 | | using Microsoft.EntityFrameworkCore; |
| | | 4 | | using Microsoft.Extensions.Logging; |
| | | 5 | | |
| | | 6 | | namespace ArturRios.Heimdall.Query.HealthChecks; |
| | | 7 | | |
| | | 8 | | /// <summary> |
| | | 9 | | /// Verifies the database connection (UC-30, FR-HC-03) by issuing a trivial read through the |
| | | 10 | | /// repository abstraction. If the query completes the connection is healthy; any failure (the |
| | | 11 | | /// database being unreachable throws on execution) is treated as unhealthy rather than |
| | | 12 | | /// propagated, so the detailed health check can still report the aggregate status (AF-30c). |
| | | 13 | | /// </summary> |
| | | 14 | | /// <remarks> |
| | | 15 | | /// The exception is swallowed so the endpoint keeps answering, but it is logged at Warning: the |
| | | 16 | | /// response says only "Unhealthy", and without the cause in the log nobody reading it has a |
| | | 17 | | /// reason to go on. |
| | | 18 | | /// </remarks> |
| | 32 | 19 | | public class DatabaseHealthCheck( |
| | 32 | 20 | | IAsyncReadOnlyRepository<Role, long> roleReader, |
| | 32 | 21 | | ILogger<DatabaseHealthCheck> logger) : IServiceHealthCheck |
| | | 22 | | { |
| | 3 | 23 | | public string ServiceName => "Database"; |
| | | 24 | | |
| | | 25 | | public async Task<bool> IsHealthyAsync() |
| | | 26 | | { |
| | | 27 | | try |
| | | 28 | | { |
| | | 29 | | // A minimal round-trip to the database — succeeds only if the connection is usable. |
| | 9 | 30 | | await roleReader.Query().AnyAsync(); |
| | | 31 | | |
| | 6 | 32 | | return true; |
| | | 33 | | } |
| | 3 | 34 | | catch (Exception exception) |
| | | 35 | | { |
| | 3 | 36 | | logger.LogWarning(exception, "The database health check failed"); |
| | | 37 | | |
| | 3 | 38 | | return false; |
| | | 39 | | } |
| | 9 | 40 | | } |
| | | 41 | | } |