|
| 1 | +// Licensed to Elasticsearch B.V under one or more agreements. |
| 2 | +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. |
| 3 | +// See the LICENSE file in the project root for more information |
| 4 | + |
| 5 | +using System.Collections.Concurrent; |
| 6 | +using System.IO.Abstractions; |
| 7 | +using Microsoft.Extensions.Logging; |
| 8 | + |
| 9 | +namespace Elastic.Documentation.Configuration.Diagram; |
| 10 | + |
| 11 | +/// <summary> |
| 12 | +/// Information about a diagram that needs to be cached |
| 13 | +/// </summary> |
| 14 | +/// <param name="LocalSvgPath">Local SVG path relative to output directory</param> |
| 15 | +/// <param name="EncodedUrl">Encoded Kroki URL for downloading</param> |
| 16 | +/// <param name="OutputDirectory">Full path to output directory</param> |
| 17 | +public record DiagramCacheInfo(string LocalSvgPath, string EncodedUrl, string OutputDirectory); |
| 18 | + |
| 19 | +/// <summary> |
| 20 | +/// Registry to track active diagrams and manage cleanup of outdated cached files |
| 21 | +/// </summary> |
| 22 | +/// <param name="writeFileSystem">File system for write/delete operations during cleanup</param> |
| 23 | +public class DiagramRegistry(IFileSystem writeFileSystem) : IDisposable |
| 24 | +{ |
| 25 | + private readonly ConcurrentDictionary<string, bool> _activeDiagrams = new(); |
| 26 | + private readonly ConcurrentDictionary<string, DiagramCacheInfo> _diagramsToCache = new(); |
| 27 | + private readonly IFileSystem _writeFileSystem = writeFileSystem; |
| 28 | + private readonly HttpClient _httpClient = new() { Timeout = TimeSpan.FromSeconds(30) }; |
| 29 | + |
| 30 | + /// <summary> |
| 31 | + /// Register a diagram for caching (collects info for later batch processing) |
| 32 | + /// </summary> |
| 33 | + /// <param name="localSvgPath">The local SVG path relative to output directory</param> |
| 34 | + /// <param name="encodedUrl">The encoded Kroki URL for downloading</param> |
| 35 | + /// <param name="outputDirectory">The full path to output directory</param> |
| 36 | + public void RegisterDiagramForCaching(string localSvgPath, string encodedUrl, string outputDirectory) |
| 37 | + { |
| 38 | + if (string.IsNullOrEmpty(localSvgPath) || string.IsNullOrEmpty(encodedUrl)) |
| 39 | + return; |
| 40 | + |
| 41 | + _ = _activeDiagrams.TryAdd(localSvgPath, true); |
| 42 | + _ = _diagramsToCache.TryAdd(localSvgPath, new DiagramCacheInfo(localSvgPath, encodedUrl, outputDirectory)); |
| 43 | + } |
| 44 | + |
| 45 | + /// <summary> |
| 46 | + /// Clear all registered diagrams (called at start of build) |
| 47 | + /// </summary> |
| 48 | + public void Clear() |
| 49 | + { |
| 50 | + _activeDiagrams.Clear(); |
| 51 | + _diagramsToCache.Clear(); |
| 52 | + } |
| 53 | + |
| 54 | + /// <summary> |
| 55 | + /// Create cached diagram files by downloading from Kroki in parallel |
| 56 | + /// </summary> |
| 57 | + /// <param name="logger">Logger for reporting download activity</param> |
| 58 | + /// <param name="readFileSystem">File system for checking existing files</param> |
| 59 | + /// <returns>Number of diagrams downloaded</returns> |
| 60 | + public async Task<int> CreateDiagramCachedFiles(ILogger logger, IFileSystem readFileSystem) |
| 61 | + { |
| 62 | + if (_diagramsToCache.IsEmpty) |
| 63 | + return 0; |
| 64 | + |
| 65 | + var downloadCount = 0; |
| 66 | + |
| 67 | + await Parallel.ForEachAsync(_diagramsToCache.Values, new ParallelOptions |
| 68 | + { |
| 69 | + MaxDegreeOfParallelism = Environment.ProcessorCount, |
| 70 | + CancellationToken = CancellationToken.None |
| 71 | + }, async (diagramInfo, ct) => |
| 72 | + { |
| 73 | + try |
| 74 | + { |
| 75 | + var fullPath = _writeFileSystem.Path.Combine(diagramInfo.OutputDirectory, diagramInfo.LocalSvgPath); |
| 76 | + |
| 77 | + // Skip if file already exists |
| 78 | + if (readFileSystem.File.Exists(fullPath)) |
| 79 | + return; |
| 80 | + |
| 81 | + // Create directory if needed |
| 82 | + var directory = _writeFileSystem.Path.GetDirectoryName(fullPath); |
| 83 | + if (directory != null && !_writeFileSystem.Directory.Exists(directory)) |
| 84 | + { |
| 85 | + _ = _writeFileSystem.Directory.CreateDirectory(directory); |
| 86 | + } |
| 87 | + |
| 88 | + // Download SVG content |
| 89 | + var svgContent = await _httpClient.GetStringAsync(diagramInfo.EncodedUrl, ct); |
| 90 | + |
| 91 | + // Validate SVG content |
| 92 | + if (string.IsNullOrWhiteSpace(svgContent) || !svgContent.Contains("<svg", StringComparison.OrdinalIgnoreCase)) |
| 93 | + { |
| 94 | + logger.LogWarning("Invalid SVG content received for diagram {LocalPath}", diagramInfo.LocalSvgPath); |
| 95 | + return; |
| 96 | + } |
| 97 | + |
| 98 | + // Write atomically using temp file |
| 99 | + var tempPath = fullPath + ".tmp"; |
| 100 | + await _writeFileSystem.File.WriteAllTextAsync(tempPath, svgContent, ct); |
| 101 | + _writeFileSystem.File.Move(tempPath, fullPath); |
| 102 | + |
| 103 | + _ = Interlocked.Increment(ref downloadCount); |
| 104 | + logger.LogDebug("Downloaded diagram: {LocalPath}", diagramInfo.LocalSvgPath); |
| 105 | + } |
| 106 | + catch (HttpRequestException ex) |
| 107 | + { |
| 108 | + logger.LogWarning("Failed to download diagram {LocalPath}: {Error}", diagramInfo.LocalSvgPath, ex.Message); |
| 109 | + } |
| 110 | + catch (TaskCanceledException ex) when (ex.InnerException is TimeoutException) |
| 111 | + { |
| 112 | + logger.LogWarning("Timeout downloading diagram {LocalPath}", diagramInfo.LocalSvgPath); |
| 113 | + } |
| 114 | + catch (Exception ex) |
| 115 | + { |
| 116 | + logger.LogWarning("Unexpected error downloading diagram {LocalPath}: {Error}", diagramInfo.LocalSvgPath, ex.Message); |
| 117 | + } |
| 118 | + }); |
| 119 | + |
| 120 | + if (downloadCount > 0) |
| 121 | + { |
| 122 | + logger.LogInformation("Downloaded {DownloadCount} diagram files from Kroki", downloadCount); |
| 123 | + } |
| 124 | + |
| 125 | + return downloadCount; |
| 126 | + } |
| 127 | + |
| 128 | + /// <summary> |
| 129 | + /// Clean up unused diagram files from the cache directory |
| 130 | + /// </summary> |
| 131 | + /// <param name="outputDirectory">The output directory containing cached diagrams</param> |
| 132 | + /// <returns>Number of files cleaned up</returns> |
| 133 | + public int CleanupUnusedDiagrams(IDirectoryInfo outputDirectory) |
| 134 | + { |
| 135 | + var graphsDir = _writeFileSystem.Path.Combine(outputDirectory.FullName, "images", "generated-graphs"); |
| 136 | + if (!_writeFileSystem.Directory.Exists(graphsDir)) |
| 137 | + return 0; |
| 138 | + |
| 139 | + var existingFiles = _writeFileSystem.Directory.GetFiles(graphsDir, "*.svg", SearchOption.AllDirectories); |
| 140 | + var cleanedCount = 0; |
| 141 | + |
| 142 | + try |
| 143 | + { |
| 144 | + foreach (var file in existingFiles) |
| 145 | + { |
| 146 | + var relativePath = _writeFileSystem.Path.GetRelativePath(outputDirectory.FullName, file); |
| 147 | + var normalizedPath = relativePath.Replace(_writeFileSystem.Path.DirectorySeparatorChar, '/'); |
| 148 | + |
| 149 | + if (!_activeDiagrams.ContainsKey(normalizedPath)) |
| 150 | + { |
| 151 | + try |
| 152 | + { |
| 153 | + _writeFileSystem.File.Delete(file); |
| 154 | + cleanedCount++; |
| 155 | + } |
| 156 | + catch |
| 157 | + { |
| 158 | + // Silent failure - cleanup is opportunistic |
| 159 | + } |
| 160 | + } |
| 161 | + } |
| 162 | + |
| 163 | + // Clean up empty directories |
| 164 | + CleanupEmptyDirectories(graphsDir); |
| 165 | + } |
| 166 | + catch |
| 167 | + { |
| 168 | + // Silent failure - cleanup is opportunistic |
| 169 | + } |
| 170 | + |
| 171 | + return cleanedCount; |
| 172 | + } |
| 173 | + |
| 174 | + private void CleanupEmptyDirectories(string directory) |
| 175 | + { |
| 176 | + try |
| 177 | + { |
| 178 | + foreach (var subDir in _writeFileSystem.Directory.GetDirectories(directory)) |
| 179 | + { |
| 180 | + CleanupEmptyDirectories(subDir); |
| 181 | + |
| 182 | + if (!_writeFileSystem.Directory.EnumerateFileSystemEntries(subDir).Any()) |
| 183 | + { |
| 184 | + try |
| 185 | + { |
| 186 | + _writeFileSystem.Directory.Delete(subDir); |
| 187 | + } |
| 188 | + catch |
| 189 | + { |
| 190 | + // Silent failure - cleanup is opportunistic |
| 191 | + } |
| 192 | + } |
| 193 | + } |
| 194 | + } |
| 195 | + catch |
| 196 | + { |
| 197 | + // Silent failure - cleanup is opportunistic |
| 198 | + } |
| 199 | + } |
| 200 | + |
| 201 | + /// <summary> |
| 202 | + /// Dispose of resources, including the HttpClient |
| 203 | + /// </summary> |
| 204 | + public void Dispose() |
| 205 | + { |
| 206 | + _httpClient.Dispose(); |
| 207 | + GC.SuppressFinalize(this); |
| 208 | + } |
| 209 | +} |
0 commit comments