using System.Text.Json; using Microsoft.Extensions.Options; using TileServer.Application; using TileServer.Application.Configuration; using TileServer.Application.Extracts; using TileServer.Domain; using TileServer.Domain.Exceptions; using TileServer.Domain.Extracts; using TileServer.Domain.Tiles; namespace TileServer.Infrastructure.Extracts; public sealed class FileExtractCatalog : IExtractCatalog { private static readonly JsonSerializerOptions JsonOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, WriteIndented = true, PropertyNameCaseInsensitive = true }; private readonly IOptionsMonitor _options; private readonly IDataPaths _paths; private readonly object _gate = new(); public FileExtractCatalog(IOptionsMonitor options, IDataPaths paths) { _options = options; _paths = paths; } public IReadOnlyList GetAll() { lock (_gate) { return MergeUnlocked().Values.OrderBy(e => e.Id, StringComparer.Ordinal).ToArray(); } } public Extract? Find(string id) { lock (_gate) { return MergeUnlocked().GetValueOrDefault(id); } } public Extract GetRequired(string id) => Find(id) ?? throw new ResourceNotFoundException("Extract", id); public async Task AddOrUpdateAsync(Extract extract, CancellationToken ct) { ResourceName.Require(extract.Id, nameof(extract.Id)); List overlay; lock (_gate) { overlay = ReadOverlayUnlocked(); var existing = overlay.FindIndex(x => string.Equals(x.Id, extract.Id, StringComparison.OrdinalIgnoreCase)); var mapped = ToOptions(extract); if (existing >= 0) { overlay[existing] = mapped; } else { overlay.Add(mapped); } } await WriteOverlayAsync(overlay, ct).ConfigureAwait(false); } public async Task RemoveAsync(string id, CancellationToken ct) { List overlay; lock (_gate) { overlay = ReadOverlayUnlocked(); var removed = overlay.RemoveAll(x => string.Equals(x.Id, id, StringComparison.OrdinalIgnoreCase)); if (removed == 0 && _options.CurrentValue.Extracts.Any(x => x.Id == id)) { throw new DomainValidationException( $"Extract '{id}' comes from appsettings and cannot be removed via API. Disable it in configuration instead."); } } await WriteOverlayAsync(overlay, ct).ConfigureAwait(false); } private Dictionary MergeUnlocked() { var map = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (var item in _options.CurrentValue.Extracts) { var extract = ToDomain(item); if (extract is not null) { map[extract.Id] = extract; } } foreach (var item in ReadOverlayUnlocked()) { var extract = ToDomain(item); if (extract is null) { continue; } if (map.TryGetValue(extract.Id, out var configured)) { extract = new Extract { Id = extract.Id, Name = extract.Name, Url = extract.Url, CenterLon = extract.CenterLon, CenterLat = extract.CenterLat, MinZoom = extract.MinZoom, MaxZoom = Math.Max(extract.MaxZoom, configured.MaxZoom), Enabled = extract.Enabled }; } map[extract.Id] = extract; } return map; } private List ReadOverlayUnlocked() { if (!File.Exists(_paths.OverlayExtractsFile)) { return []; } var json = File.ReadAllText(_paths.OverlayExtractsFile); return JsonSerializer.Deserialize>(json, JsonOptions) ?? []; } private async Task WriteOverlayAsync(List overlay, CancellationToken ct) { var json = JsonSerializer.Serialize(overlay, JsonOptions); var temp = _paths.OverlayExtractsFile + ".tmp"; await File.WriteAllTextAsync(temp, json, ct).ConfigureAwait(false); File.Move(temp, _paths.OverlayExtractsFile, overwrite: true); } private static Extract? ToDomain(ExtractOptions options) { if (!ResourceName.IsValid(options.Id) || string.IsNullOrWhiteSpace(options.Url)) { return null; } if (!Uri.TryCreate(options.Url, UriKind.Absolute, out var uri)) { return null; } var centerLon = options.Center is { Length: >= 1 } ? options.Center[0] : 37.6173; var centerLat = options.Center is { Length: >= 2 } ? options.Center[1] : 55.7558; return new Extract { Id = options.Id, Name = string.IsNullOrWhiteSpace(options.Name) ? options.Id : options.Name, Url = uri, CenterLon = centerLon, CenterLat = centerLat, MinZoom = options.MinZoom, MaxZoom = PlanetilerLimits.ClampMaxZoom(options.MaxZoom), Enabled = options.Enabled }; } private static ExtractOptions ToOptions(Extract extract) => new() { Id = extract.Id, Name = extract.Name, Url = extract.Url.ToString(), Center = [extract.CenterLon, extract.CenterLat], MinZoom = extract.MinZoom, MaxZoom = extract.MaxZoom, Enabled = extract.Enabled }; }