| | | 1 | | using System.Diagnostics; |
| | | 2 | | using Chronicis.Shared.DTOs; |
| | | 3 | | |
| | | 4 | | namespace Chronicis.Api.Services; |
| | | 5 | | |
| | | 6 | | public abstract class HealthCheckServiceBase : IHealthCheckService |
| | | 7 | | { |
| | | 8 | | private readonly ILogger _logger; |
| | | 9 | | |
| | 0 | 10 | | protected HealthCheckServiceBase(ILogger logger) |
| | | 11 | | { |
| | 0 | 12 | | _logger = logger; |
| | 0 | 13 | | } |
| | | 14 | | |
| | | 15 | | public async Task<ServiceHealthDto> CheckHealthAsync(string serviceName, string serviceKey) |
| | | 16 | | { |
| | 0 | 17 | | var stopwatch = Stopwatch.StartNew(); |
| | 0 | 18 | | var checkedAt = DateTime.UtcNow; |
| | | 19 | | |
| | | 20 | | try |
| | | 21 | | { |
| | 0 | 22 | | var (status, message) = await PerformHealthCheckAsync(); |
| | 0 | 23 | | stopwatch.Stop(); |
| | | 24 | | |
| | 0 | 25 | | return new ServiceHealthDto |
| | 0 | 26 | | { |
| | 0 | 27 | | Name = serviceName, |
| | 0 | 28 | | ServiceKey = serviceKey, |
| | 0 | 29 | | Status = status, |
| | 0 | 30 | | Message = message, |
| | 0 | 31 | | ResponseTimeMs = stopwatch.Elapsed.TotalMilliseconds, |
| | 0 | 32 | | CheckedAt = checkedAt |
| | 0 | 33 | | }; |
| | | 34 | | } |
| | 0 | 35 | | catch (Exception ex) |
| | | 36 | | { |
| | 0 | 37 | | stopwatch.Stop(); |
| | 0 | 38 | | _logger.LogError(ex, "Health check failed for {ServiceName}", serviceName); |
| | | 39 | | |
| | 0 | 40 | | return new ServiceHealthDto |
| | 0 | 41 | | { |
| | 0 | 42 | | Name = serviceName, |
| | 0 | 43 | | ServiceKey = serviceKey, |
| | 0 | 44 | | Status = HealthStatus.Unhealthy, |
| | 0 | 45 | | Message = ex.Message, |
| | 0 | 46 | | ResponseTimeMs = stopwatch.Elapsed.TotalMilliseconds, |
| | 0 | 47 | | CheckedAt = checkedAt |
| | 0 | 48 | | }; |
| | | 49 | | } |
| | 0 | 50 | | } |
| | | 51 | | |
| | | 52 | | protected abstract Task<(string Status, string? Message)> PerformHealthCheckAsync(); |
| | | 53 | | } |