using System.Globalization; using System.Text.Json; using Microsoft.Extensions.Options; using Schaad.OpenData.Traffic.Models; namespace Schaad.OpenData.Traffic.Storage; public class TrafficCacheStorage(IOptions options) { private const string DayFormat = "yyyy-MM-dd"; private const string GeometryFileName = "geometry-v5.json"; private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web) { WriteIndented = true }; private string RootPath => Path.Combine(Path.GetFullPath(options.Value.DataPath), "traffic", "thurgau"); private string CountsPath => Path.Combine(RootPath, "counts"); public virtual async Task LoadAsync(CancellationToken cancellationToken) { var stations = await ReadAsync>(Path.Combine(RootPath, "stations.json"), cancellationToken) ?? []; var geometry = await ReadAsync>(Path.Combine(RootPath, GeometryFileName), cancellationToken) ?? []; var meta = await ReadAsync(Path.Combine(RootPath, "meta.json"), cancellationToken); var counts = new List(); if (Directory.Exists(CountsPath)) { foreach (var file in Directory.EnumerateFiles(CountsPath, "*.json").Order(StringComparer.Ordinal)) { counts.AddRange(await ReadAsync>(file, cancellationToken) ?? []); } } return new TrafficSnapshot(stations, counts, geometry, meta?.LastRefresh); } public virtual async Task SaveAsync(TrafficSnapshot snapshot, IReadOnlyCollection changedDays, CancellationToken cancellationToken) { await WriteAsync(Path.Combine(RootPath, "stations.json"), snapshot.Stations.Values.OrderBy(s => s.Code).ToList(), cancellationToken); foreach (var day in changedDays) { var path = Path.Combine(CountsPath, day.ToString(DayFormat, CultureInfo.InvariantCulture) + ".json"); await WriteAsync(path, snapshot.CountsByDate.GetValueOrDefault(day).ToList(), cancellationToken); } await WriteAsync(Path.Combine(RootPath, "meta.json"), new TrafficCacheMeta(snapshot.LastRefresh), cancellationToken); } public virtual Task SaveGeometryAsync(TrafficSnapshot snapshot, CancellationToken cancellationToken) => WriteAsync(Path.Combine(RootPath, GeometryFileName), snapshot.Geometry.Values.OrderBy(g => g.StationCode).ToList(), cancellationToken); private static async Task ReadAsync(string path, CancellationToken cancellationToken) { if (!File.Exists(path)) { return default; } await using var stream = File.OpenRead(path); return await JsonSerializer.DeserializeAsync(stream, JsonOptions, cancellationToken); } private static async Task WriteAsync(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); } }