-
Notifications
You must be signed in to change notification settings - Fork 26
Add caching for Kroki diagrams #1601
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
theletterf
wants to merge
15
commits into
main
Choose a base branch
from
theletterf-add-kroki-caching
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 7 commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
e71e3ba
Add caching
theletterf 04ac6c1
Fix various issues
theletterf 1896b71
Fix lint errors
theletterf 1383eb0
Add callout
theletterf 8d0e543
Fix test
theletterf b205ac2
Fix for slashes (hopefully)
theletterf 5eae0cd
Tech review changes
theletterf d8e6429
Edits
theletterf e56d078
Merge branch 'main' into theletterf-add-kroki-caching
theletterf a92e38e
Merge branch 'main' into theletterf-add-kroki-caching
theletterf 4e3a416
Move registry to documentation set
Mpdreamz b4c88de
Fail the build on CI if new cachable SVG files are discovered
Mpdreamz d84ace3
register output file in output folder, we have to write it to both so…
Mpdreamz 2d7aae9
Merge branch 'main' into theletterf-add-kroki-caching
theletterf 4051b97
Merge branch 'main' into theletterf-add-kroki-caching
theletterf File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
209 changes: 209 additions & 0 deletions
209
src/Elastic.Documentation.Configuration/Diagram/DiagramRegistry.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,209 @@ | ||
// Licensed to Elasticsearch B.V under one or more agreements. | ||
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. | ||
// See the LICENSE file in the project root for more information | ||
|
||
using System.Collections.Concurrent; | ||
using System.IO.Abstractions; | ||
using Microsoft.Extensions.Logging; | ||
|
||
namespace Elastic.Documentation.Configuration.Diagram; | ||
|
||
/// <summary> | ||
/// Information about a diagram that needs to be cached | ||
/// </summary> | ||
/// <param name="LocalSvgPath">Local SVG path relative to output directory</param> | ||
/// <param name="EncodedUrl">Encoded Kroki URL for downloading</param> | ||
/// <param name="OutputDirectory">Full path to output directory</param> | ||
public record DiagramCacheInfo(string LocalSvgPath, string EncodedUrl, string OutputDirectory); | ||
|
||
/// <summary> | ||
/// Registry to track active diagrams and manage cleanup of outdated cached files | ||
/// </summary> | ||
/// <param name="writeFileSystem">File system for write/delete operations during cleanup</param> | ||
public class DiagramRegistry(IFileSystem writeFileSystem) : IDisposable | ||
{ | ||
private readonly ConcurrentDictionary<string, bool> _activeDiagrams = new(); | ||
private readonly ConcurrentDictionary<string, DiagramCacheInfo> _diagramsToCache = new(); | ||
private readonly IFileSystem _writeFileSystem = writeFileSystem; | ||
private readonly HttpClient _httpClient = new() { Timeout = TimeSpan.FromSeconds(30) }; | ||
|
||
/// <summary> | ||
/// Register a diagram for caching (collects info for later batch processing) | ||
/// </summary> | ||
/// <param name="localSvgPath">The local SVG path relative to output directory</param> | ||
/// <param name="encodedUrl">The encoded Kroki URL for downloading</param> | ||
/// <param name="outputDirectory">The full path to output directory</param> | ||
public void RegisterDiagramForCaching(string localSvgPath, string encodedUrl, string outputDirectory) | ||
{ | ||
if (string.IsNullOrEmpty(localSvgPath) || string.IsNullOrEmpty(encodedUrl)) | ||
return; | ||
|
||
_ = _activeDiagrams.TryAdd(localSvgPath, true); | ||
_ = _diagramsToCache.TryAdd(localSvgPath, new DiagramCacheInfo(localSvgPath, encodedUrl, outputDirectory)); | ||
} | ||
|
||
/// <summary> | ||
/// Clear all registered diagrams (called at start of build) | ||
/// </summary> | ||
public void Clear() | ||
{ | ||
_activeDiagrams.Clear(); | ||
_diagramsToCache.Clear(); | ||
} | ||
|
||
/// <summary> | ||
/// Create cached diagram files by downloading from Kroki in parallel | ||
/// </summary> | ||
/// <param name="logger">Logger for reporting download activity</param> | ||
/// <param name="readFileSystem">File system for checking existing files</param> | ||
/// <returns>Number of diagrams downloaded</returns> | ||
public async Task<int> CreateDiagramCachedFiles(ILogger logger, IFileSystem readFileSystem) | ||
{ | ||
if (_diagramsToCache.IsEmpty) | ||
return 0; | ||
|
||
var downloadCount = 0; | ||
|
||
await Parallel.ForEachAsync(_diagramsToCache.Values, new ParallelOptions | ||
{ | ||
MaxDegreeOfParallelism = Environment.ProcessorCount, | ||
CancellationToken = CancellationToken.None | ||
}, async (diagramInfo, ct) => | ||
{ | ||
try | ||
{ | ||
var fullPath = _writeFileSystem.Path.Combine(diagramInfo.OutputDirectory, diagramInfo.LocalSvgPath); | ||
|
||
// Skip if file already exists | ||
if (readFileSystem.File.Exists(fullPath)) | ||
return; | ||
|
||
// Create directory if needed | ||
var directory = _writeFileSystem.Path.GetDirectoryName(fullPath); | ||
if (directory != null && !_writeFileSystem.Directory.Exists(directory)) | ||
{ | ||
_ = _writeFileSystem.Directory.CreateDirectory(directory); | ||
} | ||
|
||
// Download SVG content | ||
var svgContent = await _httpClient.GetStringAsync(diagramInfo.EncodedUrl, ct); | ||
|
||
// Validate SVG content | ||
if (string.IsNullOrWhiteSpace(svgContent) || !svgContent.Contains("<svg", StringComparison.OrdinalIgnoreCase)) | ||
{ | ||
logger.LogWarning("Invalid SVG content received for diagram {LocalPath}", diagramInfo.LocalSvgPath); | ||
return; | ||
} | ||
|
||
// Write atomically using temp file | ||
var tempPath = fullPath + ".tmp"; | ||
await _writeFileSystem.File.WriteAllTextAsync(tempPath, svgContent, ct); | ||
_writeFileSystem.File.Move(tempPath, fullPath); | ||
|
||
_ = Interlocked.Increment(ref downloadCount); | ||
logger.LogDebug("Downloaded diagram: {LocalPath}", diagramInfo.LocalSvgPath); | ||
} | ||
catch (HttpRequestException ex) | ||
{ | ||
logger.LogWarning("Failed to download diagram {LocalPath}: {Error}", diagramInfo.LocalSvgPath, ex.Message); | ||
} | ||
catch (TaskCanceledException ex) when (ex.InnerException is TimeoutException) | ||
{ | ||
logger.LogWarning("Timeout downloading diagram {LocalPath}", diagramInfo.LocalSvgPath); | ||
} | ||
catch (Exception ex) | ||
{ | ||
logger.LogWarning("Unexpected error downloading diagram {LocalPath}: {Error}", diagramInfo.LocalSvgPath, ex.Message); | ||
} | ||
}); | ||
|
||
if (downloadCount > 0) | ||
{ | ||
logger.LogInformation("Downloaded {DownloadCount} diagram files from Kroki", downloadCount); | ||
} | ||
|
||
return downloadCount; | ||
} | ||
|
||
/// <summary> | ||
/// Clean up unused diagram files from the cache directory | ||
/// </summary> | ||
/// <param name="outputDirectory">The output directory containing cached diagrams</param> | ||
/// <returns>Number of files cleaned up</returns> | ||
public int CleanupUnusedDiagrams(IDirectoryInfo outputDirectory) | ||
{ | ||
var graphsDir = _writeFileSystem.Path.Combine(outputDirectory.FullName, "images", "generated-graphs"); | ||
if (!_writeFileSystem.Directory.Exists(graphsDir)) | ||
return 0; | ||
|
||
var existingFiles = _writeFileSystem.Directory.GetFiles(graphsDir, "*.svg", SearchOption.AllDirectories); | ||
var cleanedCount = 0; | ||
|
||
try | ||
{ | ||
foreach (var file in existingFiles) | ||
{ | ||
var relativePath = _writeFileSystem.Path.GetRelativePath(outputDirectory.FullName, file); | ||
var normalizedPath = relativePath.Replace(_writeFileSystem.Path.DirectorySeparatorChar, '/'); | ||
|
||
if (!_activeDiagrams.ContainsKey(normalizedPath)) | ||
{ | ||
try | ||
{ | ||
_writeFileSystem.File.Delete(file); | ||
cleanedCount++; | ||
} | ||
catch | ||
{ | ||
// Silent failure - cleanup is opportunistic | ||
} | ||
} | ||
} | ||
|
||
// Clean up empty directories | ||
CleanupEmptyDirectories(graphsDir); | ||
} | ||
catch | ||
{ | ||
// Silent failure - cleanup is opportunistic | ||
} | ||
|
||
return cleanedCount; | ||
} | ||
|
||
private void CleanupEmptyDirectories(string directory) | ||
{ | ||
try | ||
{ | ||
foreach (var subDir in _writeFileSystem.Directory.GetDirectories(directory)) | ||
{ | ||
CleanupEmptyDirectories(subDir); | ||
|
||
if (!_writeFileSystem.Directory.EnumerateFileSystemEntries(subDir).Any()) | ||
{ | ||
try | ||
{ | ||
_writeFileSystem.Directory.Delete(subDir); | ||
} | ||
catch | ||
{ | ||
// Silent failure - cleanup is opportunistic | ||
} | ||
} | ||
} | ||
} | ||
catch | ||
{ | ||
// Silent failure - cleanup is opportunistic | ||
} | ||
} | ||
|
||
/// <summary> | ||
/// Dispose of resources, including the HttpClient | ||
/// </summary> | ||
public void Dispose() | ||
{ | ||
_httpClient.Dispose(); | ||
GC.SuppressFinalize(this); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.