using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using TileServer.Application.Configuration; using TileServer.Application.Styles; using TileServer.Application.Sync; using TileServer.Domain.Exceptions; namespace TileServer.Infrastructure.Sync; public sealed class MapSyncHostedService( IMapSyncService sync, ISyncSchedulerClock clock, IStyleCatalog styles, IOptions options, ILogger logger) : BackgroundService { protected override async Task ExecuteAsync(CancellationToken stoppingToken) { try { await styles.SeedDefaultsAsync(stoppingToken).ConfigureAwait(false); } catch (Exception ex) when (ex is not OperationCanceledException) { logger.LogWarning(ex, "Failed to seed default map styles."); } sync.SetNextScheduledAt(clock.GetNextOccurrence(DateTimeOffset.UtcNow)); if (options.Value.Sync.RunOnStartup) { logger.LogInformation("Running initial OSM extract synchronization."); await RunSafelyAsync(stoppingToken).ConfigureAwait(false); } while (!stoppingToken.IsCancellationRequested) { var now = DateTimeOffset.UtcNow; var next = clock.GetNextOccurrence(now); sync.SetNextScheduledAt(next); if (next is null) { logger.LogWarning("Sync cron '{Cron}' has no future occurrence.", options.Value.Sync.Cron); break; } var delay = next.Value - now; if (delay < TimeSpan.Zero) { delay = TimeSpan.Zero; } logger.LogInformation("Next OSM extract sync at {Next}.", next); try { await Task.Delay(delay, stoppingToken).ConfigureAwait(false); } catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; } await RunSafelyAsync(stoppingToken).ConfigureAwait(false); } } private async Task RunSafelyAsync(CancellationToken ct) { try { await sync.RunAllAsync(ct).ConfigureAwait(false); } catch (ResourceConflictException) { logger.LogInformation("Sync already in progress, skip scheduled run."); } catch (OperationCanceledException) when (ct.IsCancellationRequested) { } catch (Exception ex) { logger.LogError(ex, "Scheduled map synchronization failed."); } } }