using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Schaad.OpenData.Weather.Models; using Schaad.OpenData.Weather.Source; using Schaad.OpenData.Weather.Storage; namespace Schaad.OpenData.Weather; public class WeatherRefresher( MeteoSwissClient client, WeatherCacheStorage storage, WeatherDataStore store, IOptions options, TimeProvider timeProvider, ILogger logger) { private static readonly TimeSpan StationsInterval = TimeSpan.FromDays(1); private static readonly TimeSpan BackfillWindow = TimeSpan.FromDays(7); private static readonly TimeSpan RequiredCoverage = TimeSpan.FromDays(6); private static readonly TimeSpan MaxGap = TimeSpan.FromHours(20); private static readonly TimeSpan BackfillRetry = TimeSpan.FromHours(1); private readonly Dictionary lastBackfill = []; public async Task LoadCacheAsync(CancellationToken cancellationToken) { var snapshot = await storage.LoadAsync(cancellationToken); store.Replace(snapshot); logger.LogInformation( "Loaded weather cache with {Stations} stations and {Readings} readings", snapshot.Stations.Count, snapshot.Readings.Count); } public bool IsRefreshDue(TimeSpan interval) => store.Current.LastRefresh is not { } lastRefresh || timeProvider.GetUtcNow() - lastRefresh >= interval; public async Task RefreshAsync(CancellationToken cancellationToken) { var now = timeProvider.GetUtcNow(); var current = store.Current; var abbreviations = options.Value.EffectiveStations; IReadOnlyList stations = []; DateTimeOffset? stationsFetched = null; if (current.StationsFetched is not { } fetched || now - fetched >= StationsInterval || abbreviations.Any(a => current.Stations.All(s => s.Abbr != a))) { stations = await client.FetchStationsAsync(abbreviations, cancellationToken); stationsFetched = now; } var byStation = current.Readings.ToLookup(r => r.StationAbbr); var fetchedReadings = new List(); var backfilled = 0; foreach (var abbr in abbreviations) { try { if (NeedsBackfill(byStation[abbr].ToList(), now) && (!lastBackfill.TryGetValue(abbr, out var last) || now - last >= BackfillRetry)) { lastBackfill[abbr] = now; var history = await client.FetchHistoryAsync(abbr, now - BackfillWindow, cancellationToken); backfilled += history.Count; fetchedReadings.AddRange(history); } fetchedReadings.AddRange(await client.FetchRecentAsync(abbr, cancellationToken)); } catch (Exception exception) when (exception is HttpRequestException or IOException or TaskCanceledException && !cancellationToken.IsCancellationRequested) { logger.LogWarning(exception, "Could not fetch weather station {Station}", abbr); } } var added = current.NewReadings(fetchedReadings); var firstKeptDay = DateOnly.FromDateTime(now.UtcDateTime).AddDays(-options.Value.HistoryDays); var keepFrom = new DateTimeOffset(firstKeptDay.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero); var updated = current.With(stations, fetchedReadings, now, stationsFetched, keepFrom); var changedDays = added .Select(r => DateOnly.FromDateTime(r.Time.UtcDateTime)) .Where(day => day >= firstKeptDay) .Distinct() .ToList(); await storage.SaveAsync(updated, changedDays, cancellationToken); storage.DeleteDaysBefore(firstKeptDay); store.Replace(updated); logger.LogInformation( "Fetched weather for {Stations} stations, {Added} new readings ({Backfilled} from the recent files)", abbreviations.Count, added.Count, backfilled); } private static bool NeedsBackfill(IReadOnlyList readings, DateTimeOffset now) => readings.Count == 0 || readings[0].Time > now - RequiredCoverage || readings[^1].Time < now - MaxGap; }