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>
67 lines
2.5 KiB
C#
67 lines
2.5 KiB
C#
using System.Globalization;
|
|
using System.Text.Json;
|
|
using Microsoft.Extensions.Options;
|
|
using Schaad.OpenData.Watercraft.Models;
|
|
|
|
namespace Schaad.OpenData.Watercraft.Storage;
|
|
|
|
public class WatercraftCacheStorage(IOptions<WatercraftOptions> options)
|
|
{
|
|
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web);
|
|
|
|
private string RootPath => Path.Combine(Path.GetFullPath(options.Value.DataPath), "watercraft", "thurgau");
|
|
|
|
private string YearsPath => Path.Combine(RootPath, "years");
|
|
|
|
public virtual async Task<WatercraftSnapshot> LoadAsync(CancellationToken cancellationToken)
|
|
{
|
|
var meta = await ReadAsync<WatercraftCacheMeta>(Path.Combine(RootPath, "meta.json"), cancellationToken);
|
|
var years = new List<VesselYear>();
|
|
if (Directory.Exists(YearsPath))
|
|
{
|
|
foreach (var file in Directory.EnumerateFiles(YearsPath, "*.json").Order(StringComparer.Ordinal))
|
|
{
|
|
if (await ReadAsync<VesselYear>(file, cancellationToken) is { } year)
|
|
{
|
|
years.Add(year);
|
|
}
|
|
}
|
|
}
|
|
|
|
return new WatercraftSnapshot(years, meta?.LastRefresh);
|
|
}
|
|
|
|
public virtual async Task SaveAsync(WatercraftSnapshot snapshot, IReadOnlyCollection<int> changedYears, CancellationToken cancellationToken)
|
|
{
|
|
foreach (var year in snapshot.Years.Where(y => changedYears.Contains(y.Year)))
|
|
{
|
|
var path = Path.Combine(YearsPath, year.Year.ToString(CultureInfo.InvariantCulture) + ".json");
|
|
await WriteAsync(path, year, cancellationToken);
|
|
}
|
|
|
|
await WriteAsync(Path.Combine(RootPath, "meta.json"), new WatercraftCacheMeta(snapshot.LastRefresh), cancellationToken);
|
|
}
|
|
|
|
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);
|
|
}
|
|
}
|