OpenDataVisualizer/Schaad.OpenData.Hydrology/Storage/HydrologyCacheStorage.cs
Claudio Schaad a838b17dc1 Add live water layer from BAFU hydrology data
- 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>
2026-11-18 20:40:33 +01:00

88 lines
3.3 KiB
C#

using System.Globalization;
using System.Text.Json;
using Microsoft.Extensions.Options;
using Schaad.OpenData.Hydrology.Models;
namespace Schaad.OpenData.Hydrology.Storage;
public class HydrologyCacheStorage(IOptions<HydrologyOptions> options)
{
private const string DayFormat = "yyyy-MM-dd";
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web);
private string RootPath => Path.Combine(Path.GetFullPath(options.Value.DataPath), "hydrology", "thurgau");
private string DaysPath => Path.Combine(RootPath, "days");
public virtual async Task<HydrologySnapshot> LoadAsync(CancellationToken cancellationToken)
{
var meta = await ReadAsync<HydrologyCacheMeta>(Path.Combine(RootPath, "meta.json"), cancellationToken);
var stations = await ReadAsync<List<HydroStation>>(Path.Combine(RootPath, "stations.json"), cancellationToken) ?? [];
var readings = new List<HydroReading>();
if (Directory.Exists(DaysPath))
{
foreach (var file in Directory.EnumerateFiles(DaysPath, "*.json").Order(StringComparer.Ordinal))
{
readings.AddRange(await ReadAsync<List<HydroReading>>(file, cancellationToken) ?? []);
}
}
return new HydrologySnapshot(stations, readings, meta?.LastRefresh);
}
public virtual async Task SaveAsync(HydrologySnapshot snapshot, IReadOnlyCollection<DateOnly> changedDays, CancellationToken cancellationToken)
{
var byDay = snapshot.Readings.ToLookup(r => DateOnly.FromDateTime(r.Time.UtcDateTime));
foreach (var day in changedDays)
{
await WriteAsync(DayPath(day), byDay[day].ToList(), cancellationToken);
}
await WriteAsync(Path.Combine(RootPath, "stations.json"), snapshot.Stations, cancellationToken);
await WriteAsync(Path.Combine(RootPath, "meta.json"), new HydrologyCacheMeta(snapshot.LastRefresh), cancellationToken);
}
public virtual void DeleteDaysBefore(DateOnly firstKeptDay)
{
if (!Directory.Exists(DaysPath))
{
return;
}
foreach (var file in Directory.EnumerateFiles(DaysPath, "*.json"))
{
if (DateOnly.TryParseExact(Path.GetFileNameWithoutExtension(file), DayFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out var day)
&& day < firstKeptDay)
{
File.Delete(file);
}
}
}
private string DayPath(DateOnly day) =>
Path.Combine(DaysPath, day.ToString(DayFormat, CultureInfo.InvariantCulture) + ".json");
private static async Task<T?> ReadAsync<T>(string path, CancellationToken cancellationToken)
{
if (!File.Exists(path))
{
return default;
}
await using var stream = File.OpenRead(path);
return await JsonSerializer.DeserializeAsync<T>(stream, JsonOptions, cancellationToken);
}
private static async Task WriteAsync<T>(string path, T value, CancellationToken cancellationToken)
{
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
var tempPath = path + ".tmp";
await using (var stream = File.Create(tempPath))
{
await JsonSerializer.SerializeAsync(stream, value, JsonOptions, cancellationToken);
}
File.Move(tempPath, path, true);
}
}