Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Claudio Schaad <c.schaad@pog.ch> Co-committed-by: Claudio Schaad <c.schaad@pog.ch>
46 lines
1.8 KiB
C#
46 lines
1.8 KiB
C#
using Microsoft.Extensions.Logging;
|
|
using Schaad.OpenData.Watercraft.Models;
|
|
using Schaad.OpenData.Watercraft.Source;
|
|
using Schaad.OpenData.Watercraft.Storage;
|
|
|
|
namespace Schaad.OpenData.Watercraft;
|
|
|
|
public class WatercraftRefresher(
|
|
ThurgauWatercraftClient client,
|
|
WatercraftCacheStorage storage,
|
|
WatercraftDataStore store,
|
|
TimeProvider timeProvider,
|
|
ILogger<WatercraftRefresher> logger)
|
|
{
|
|
public async Task LoadCacheAsync(CancellationToken cancellationToken)
|
|
{
|
|
var snapshot = await storage.LoadAsync(cancellationToken);
|
|
store.Replace(snapshot);
|
|
logger.LogInformation("Loaded watercraft cache with {Years} years", 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 datasets = await client.FindDatasetsAsync(cancellationToken);
|
|
var changed = new List<VesselYear>();
|
|
foreach (var dataset in datasets.Where(d => IsOutdated(current.FindYear(d.Year), d)))
|
|
{
|
|
changed.Add(await client.FetchAsync(dataset, cancellationToken));
|
|
}
|
|
|
|
var updated = current.With(changed, timeProvider.GetUtcNow());
|
|
await storage.SaveAsync(updated, changed.Select(y => y.Year).ToList(), cancellationToken);
|
|
store.Replace(updated);
|
|
logger.LogInformation(
|
|
"Found {Datasets} watercraft datasets, imported {Imported} of them",
|
|
datasets.Count,
|
|
changed.Count);
|
|
}
|
|
|
|
private static bool IsOutdated(VesselYear? cached, VesselDataset dataset) =>
|
|
cached is null || cached.DatasetId != dataset.DatasetId || cached.Modified != dataset.Modified;
|
|
}
|