using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Schaad.OpenData.Vehicles.Models; using Schaad.OpenData.Vehicles.Source; using Schaad.OpenData.Vehicles.Storage; namespace Schaad.OpenData.Vehicles; public class VehicleRefresher( ThurgauVehicleClient client, MunicipalityBoundaryClient boundaryClient, VehicleCacheStorage storage, VehicleDataStore store, IOptions options, TimeProvider timeProvider, ILogger logger) { public async Task LoadCacheAsync(CancellationToken cancellationToken) { var snapshot = await storage.LoadAsync(cancellationToken); store.Replace(snapshot); logger.LogInformation( "Loaded vehicle cache with {Entries} stock entries for {Years} years", snapshot.Stock.Count, snapshot.Years.Count); } public bool IsRefreshDue(TimeSpan interval) => store.Current.LastRefresh is not { } lastRefresh || timeProvider.GetUtcNow() - lastRefresh >= interval; public async Task RefreshAsync(CancellationToken cancellationToken) { var current = store.Current; var stockVersion = await client.GetVersionAsync(options.Value.StockDatasetId, cancellationToken); var populationVersion = await client.GetVersionAsync(options.Value.PopulationDatasetId, cancellationToken); var stockChanged = current.Stock.Count == 0 || current.StockVersion != stockVersion; var populationChanged = current.Population.Count == 0 || current.PopulationVersion != populationVersion; var stock = stockChanged ? await client.FetchStockAsync(cancellationToken) : current.Stock; var population = populationChanged ? await client.FetchPopulationAsync(cancellationToken) : current.Population; var outlines = await CompleteOutlinesAsync(current.Outlines, stock, cancellationToken); var updated = new VehicleSnapshot(stock, population, outlines, stockVersion, populationVersion, timeProvider.GetUtcNow()); await storage.SaveAsync(updated, cancellationToken); store.Replace(updated); logger.LogInformation( "Vehicle refresh: stock {StockState} ({Entries} entries), population {PopulationState}, {Outlines} municipality outlines", stockChanged ? "imported" : "unchanged", stock.Count, populationChanged ? "imported" : "unchanged", outlines.Count); } private async Task> CompleteOutlinesAsync( IReadOnlyList cached, IReadOnlyList stock, CancellationToken cancellationToken) { var outlines = cached.ToList(); var known = outlines.Select(o => o.Id).ToHashSet(StringComparer.Ordinal); foreach (var id in stock.Select(e => e.MunicipalityId).Distinct(StringComparer.Ordinal).Where(id => !known.Contains(id))) { if (await boundaryClient.FetchAsync(id, cancellationToken) is { } outline) { outlines.Add(outline); } else { logger.LogWarning("No boundary found for municipality {MunicipalityId}", id); } } return outlines; } }