- New Schaad.OpenData.Hydrology project: LindasHydroClient fetches the
current level, discharge, water temperature and danger level of nine
BAFU stations around Thurgau from LINDAS every 10 minutes
- LINDAS has no history, so the server keeps readings per day (60 days)
and fills gaps from the 7-day plot JSON of hydrodaten.admin.ch
- API: /api/hydrology/meta, /stations, /stations/{id}/history
- Combined map: "Gewässer (live)" layer with river circles (size by
discharge, colour by danger level or water temperature), lake level
badges, station panel with 7-day chart, overview and municipality
context entries
- Docs: docs/datasets/gewaesser.md, overview in docs/datasets.md,
CLAUDE.md; Docker and appsettings wiring
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
102 lines
4.1 KiB
C#
102 lines
4.1 KiB
C#
using Microsoft.Extensions.Logging;
|
|
using Microsoft.Extensions.Options;
|
|
using Schaad.OpenData.Hydrology.Models;
|
|
using Schaad.OpenData.Hydrology.Source;
|
|
using Schaad.OpenData.Hydrology.Storage;
|
|
|
|
namespace Schaad.OpenData.Hydrology;
|
|
|
|
public class HydrologyRefresher(
|
|
LindasHydroClient client,
|
|
HydrodatenPlotClient plotClient,
|
|
HydrologyCacheStorage storage,
|
|
HydrologyDataStore store,
|
|
IOptions<HydrologyOptions> options,
|
|
TimeProvider timeProvider,
|
|
ILogger<HydrologyRefresher> logger)
|
|
{
|
|
private static readonly TimeSpan RequiredCoverage = TimeSpan.FromDays(6);
|
|
private static readonly TimeSpan MaxGap = TimeSpan.FromMinutes(45);
|
|
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 hydrology 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 measurements = await client.FetchAsync(options.Value.EffectiveStationIds.ToList(), cancellationToken);
|
|
var backfilled = await BackfillAsync(current, measurements.Stations, now, cancellationToken);
|
|
var combined = new HydroMeasurements(
|
|
measurements.Stations,
|
|
current.NewReadings(backfilled).Concat(measurements.Readings).ToList());
|
|
|
|
var added = current.NewReadings(combined.Readings);
|
|
var firstKeptDay = DateOnly.FromDateTime(now.UtcDateTime).AddDays(-options.Value.HistoryDays);
|
|
var keepFrom = new DateTimeOffset(firstKeptDay.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero);
|
|
|
|
var updated = current.With(combined, now, 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 {Stations} hydrology stations, {Added} new readings ({Backfilled} from hydrodaten.admin.ch)",
|
|
measurements.Stations.Count,
|
|
added.Count,
|
|
backfilled.Count);
|
|
}
|
|
|
|
private async Task<IReadOnlyList<HydroReading>> BackfillAsync(
|
|
HydrologySnapshot current,
|
|
IReadOnlyList<HydroStation> stations,
|
|
DateTimeOffset now,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
var byStation = current.Readings.ToLookup(r => r.StationId);
|
|
var readings = new List<HydroReading>();
|
|
foreach (var station in stations)
|
|
{
|
|
if (!NeedsBackfill(byStation[station.Id].ToList(), now)
|
|
|| (lastBackfill.TryGetValue(station.Id, out var last) && now - last < BackfillRetry))
|
|
{
|
|
continue;
|
|
}
|
|
|
|
lastBackfill[station.Id] = now;
|
|
try
|
|
{
|
|
readings.AddRange(await plotClient.FetchRecentAsync(station.Id, cancellationToken));
|
|
}
|
|
catch (Exception exception) when (exception is HttpRequestException or System.Text.Json.JsonException or TaskCanceledException
|
|
&& !cancellationToken.IsCancellationRequested)
|
|
{
|
|
logger.LogWarning(exception, "Could not backfill hydrology station {Station}", station.Id);
|
|
}
|
|
}
|
|
|
|
return readings;
|
|
}
|
|
|
|
private static bool NeedsBackfill(IReadOnlyList<HydroReading> readings, DateTimeOffset now) =>
|
|
readings.Count == 0
|
|
|| readings[0].Time > now - RequiredCoverage
|
|
|| readings[^1].Time < now - MaxGap;
|
|
}
|