using Microsoft.Extensions.Options; using Tiku.Application.Security; using Tiku.Application.Tenancy; namespace Tiku.Worker; public class Worker( IServiceScopeFactory scopeFactory, IOptions options, ILogger logger) : BackgroundService { protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { try { await using var scope = scopeFactory.CreateAsyncScope(); scope.ServiceProvider.GetRequiredService() .InitializeSystem(null, "Tenant domain DNS and TLS lifecycle worker"); var processed = await scope.ServiceProvider .GetRequiredService() .ProcessPendingAsync(stoppingToken); if (processed > 0) { logger.LogInformation("Processed {Count} pending tenant domains.", processed); } } catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; } catch (Exception exception) { logger.LogError(exception, "Tenant domain lifecycle processing failed."); } await Task.Delay( TimeSpan.FromSeconds(Math.Clamp(options.Value.PollSeconds, 10, 3600)), stoppingToken); } } }