This commit is contained in:
2024-01-23 17:50:29 +01:00
parent 26b1f60948
commit 26e3226ae9
16 changed files with 307 additions and 0 deletions

View File

@@ -0,0 +1,34 @@
using HealtRegistry.Models;
using Microsoft.Extensions.Options;
namespace HealtRegistry.Services;
public class HealthService : IHealthService
{
public Dictionary<string, ServiceHealthData> ServiceHealthes { get; } = new();
public HealthService(IOptions<ServicesConfiguration> servicesConfiguration)
{
foreach (var service in servicesConfiguration.Value.Services)
{
ServiceHealthes.Add(service.Key, new ServiceHealthData()
{
Healthy = service.Value.DefaultValue,
LastUpdated = DateTimeOffset.Now
});
}
}
public ServiceHealthes GetServiceHealthes()
{
var serviceHealthes = ServiceHealthes.ToDictionary(x => x.Key, x => new ServiceHealth(x.Value.Healthy));
return new ServiceHealthes(serviceHealthes);
}
public void SetServiceHealth(string serviceName, bool health)
{
ServiceHealthes[serviceName].Healthy = health;
ServiceHealthes[serviceName].LastUpdated = DateTimeOffset.Now;
}
}

View File

@@ -0,0 +1,51 @@
using HealtRegistry.Models;
using Microsoft.Extensions.Options;
namespace HealtRegistry.Services;
public class HealthTimeoutService : BackgroundService
{
private readonly IHealthService _healthService;
private readonly IOptionsMonitor<ServicesConfiguration> _servicesConfiguration;
private readonly ILogger<HealthTimeoutService> _logger;
public HealthTimeoutService(
IHealthService healthService,
IOptionsMonitor<ServicesConfiguration> servicesConfiguration,
ILogger<HealthTimeoutService> logger
)
{
_healthService = healthService;
_servicesConfiguration = servicesConfiguration;
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
var now = DateTimeOffset.Now;
foreach (var service in _healthService.ServiceHealthes)
{
if (!service.Value.Healthy) continue;
var serviceConfiguration = _servicesConfiguration.CurrentValue.Services.TryGetValue(service.Key, out var configuration)
? configuration
: null;
if (serviceConfiguration is not null &&
now - service.Value.LastUpdated > serviceConfiguration.Timeout)
{
_logger.LogInformation("Service {ServiceName} is timed out", service.Key);
_healthService.SetServiceHealth(service.Key, false);
}
}
try
{
await Task.Delay(1000, stoppingToken);
}
catch { }
}
}
}

View File

@@ -0,0 +1,10 @@
using HealtRegistry.Models;
namespace HealtRegistry.Services;
public interface IHealthService
{
Dictionary<string, ServiceHealthData> ServiceHealthes { get; }
ServiceHealthes GetServiceHealthes();
void SetServiceHealth(string serviceName, bool health);
}