- New Schaad.OpenData.Weather project: MeteoSwissClient reads the
10-minute CSV of the five SwissMetNet stations in Thurgau every 10
minutes (station list once a day) and backfills the last 7 days from
the yearly file when the cache has less than 6 days
- History kept as JSON per day (60 days); a failing station does not
stop the others
- API: /api/weather/meta, /stations (current values, 1 h/24 h rain,
24 h min/max, strongest gust), /stations/{abbr}/history
- Combined map: "Wetter (live)" layer with station badges (temperature,
24 h rain or wind), wind arrows, rain marker, station panel with
hourly 7-day chart, overview and municipality context entries
- Docs: docs/datasets/wetter.md, overview in docs/datasets.md,
CLAUDE.md; Docker and appsettings wiring
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>
102 lines
4.3 KiB
C#
102 lines
4.3 KiB
C#
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<WeatherOptions> options,
|
|
TimeProvider timeProvider,
|
|
ILogger<WeatherRefresher> 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<string, DateTimeOffset> 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<WeatherStation> 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<WeatherReading>();
|
|
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<WeatherReading> readings, DateTimeOffset now) =>
|
|
readings.Count == 0
|
|
|| readings[0].Time > now - RequiredCoverage
|
|
|| readings[^1].Time < now - MaxGap;
|
|
}
|