using HealtRegistry.Models; using Microsoft.Extensions.Options; namespace HealtRegistry.Services; public class HealthTimeoutService : BackgroundService { private readonly IHealthService _healthService; private readonly IOptionsMonitor _servicesConfiguration; private readonly ILogger _logger; public HealthTimeoutService( IHealthService healthService, IOptionsMonitor servicesConfiguration, ILogger 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 { } } } }