XAML-Map-Control/MapControl/Shared/ImageFileCache.cs

364 lines
12 KiB
C#
Raw Normal View History

2025-02-27 18:46:32 +01:00
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Memory;
2025-03-30 16:35:10 +02:00
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
2021-06-30 17:56:02 +02:00
using System;
using System.IO;
2021-06-30 20:59:38 +02:00
using System.Linq;
2024-02-03 20:53:32 +01:00
using System.Threading;
2021-06-30 20:59:38 +02:00
using System.Threading.Tasks;
2021-06-30 17:56:02 +02:00
namespace MapControl.Caching
{
2025-03-30 16:35:10 +02:00
public class ImageFileCacheOptions : IOptions<ImageFileCacheOptions>
{
public ImageFileCacheOptions Value => this;
public string Path { get; set; }
public TimeSpan ExpirationScanFrequency { get; set; } = TimeSpan.FromHours(1);
}
2021-06-30 17:56:02 +02:00
/// <summary>
2025-03-29 18:53:23 +01:00
/// IDistributedCache implementation that creates a single file per cache entry.
/// The cache expiration time is stored in the file's CreationTime property.
2021-06-30 17:56:02 +02:00
/// </summary>
2025-11-14 23:59:24 +01:00
public sealed class ImageFileCache : IDistributedCache, IDisposable
2021-06-30 17:56:02 +02:00
{
2025-02-20 20:29:49 +01:00
private readonly MemoryDistributedCache memoryCache;
private readonly DirectoryInfo rootDirectory;
2025-02-20 20:29:49 +01:00
private readonly Timer expirationScanTimer;
2025-03-30 16:35:10 +02:00
private readonly ILogger logger;
2025-02-20 20:29:49 +01:00
private bool scanningExpiration;
2021-06-30 17:56:02 +02:00
2025-03-30 16:35:10 +02:00
public ImageFileCache(string path, ILoggerFactory loggerFactory = null)
: this(new ImageFileCacheOptions { Path = path }, loggerFactory)
{
}
public ImageFileCache(IOptions<ImageFileCacheOptions> optionsAccessor, ILoggerFactory loggerFactory = null)
: this(optionsAccessor.Value, loggerFactory)
{
}
2025-03-30 16:35:10 +02:00
public ImageFileCache(ImageFileCacheOptions options, ILoggerFactory loggerFactory = null)
2021-06-30 17:56:02 +02:00
{
2025-03-30 16:35:10 +02:00
var path = options.Path;
2025-03-09 21:40:37 +01:00
rootDirectory = new DirectoryInfo(!string.IsNullOrEmpty(path) ? path : "TileCache");
2025-02-20 11:45:45 +01:00
rootDirectory.Create();
2021-07-01 15:43:52 +02:00
2025-09-19 18:48:05 +02:00
logger = loggerFactory?.CreateLogger(typeof(ImageFileCache));
2025-03-30 16:35:10 +02:00
logger?.LogInformation("Started in {name}", rootDirectory.FullName);
2025-03-30 16:35:10 +02:00
var memoryCacheOptions = new MemoryDistributedCacheOptions();
2025-02-20 20:29:49 +01:00
2025-03-30 16:35:10 +02:00
if (options.ExpirationScanFrequency > TimeSpan.Zero)
{
2025-03-30 16:35:10 +02:00
memoryCacheOptions.ExpirationScanFrequency = options.ExpirationScanFrequency;
2025-02-20 20:29:49 +01:00
2025-03-30 16:35:10 +02:00
expirationScanTimer = new Timer(_ => DeleteExpiredItems(), null, TimeSpan.Zero, options.ExpirationScanFrequency);
}
2025-02-20 20:29:49 +01:00
2025-03-30 16:35:10 +02:00
memoryCache = new MemoryDistributedCache(Options.Create(memoryCacheOptions));
}
2021-06-30 17:56:02 +02:00
public void Dispose()
{
2025-02-20 20:29:49 +01:00
expirationScanTimer?.Dispose();
2021-06-30 20:59:38 +02:00
}
2024-02-03 20:53:32 +01:00
public byte[] Get(string key)
{
byte[] value = null;
2024-02-03 20:53:32 +01:00
if (!string.IsNullOrEmpty(key))
2024-02-03 20:53:32 +01:00
{
value = memoryCache.Get(key);
if (value == null)
2024-02-03 20:53:32 +01:00
{
var file = GetFile(key);
try
{
if (file != null && file.Exists && file.CreationTime > DateTime.Now)
{
value = ReadAllBytes(file);
var options = new DistributedCacheEntryOptions { AbsoluteExpiration = file.CreationTime };
memoryCache.Set(key, value, options);
2025-05-08 19:51:31 +02:00
2025-08-22 11:06:37 +02:00
logger?.LogDebug("Read {name}", file.FullName);
}
}
catch (Exception ex)
{
2025-03-30 16:35:10 +02:00
logger?.LogError(ex, "Failed reading {name}", file.FullName);
}
2024-02-03 20:53:32 +01:00
}
}
return value;
2024-02-03 20:53:32 +01:00
}
public async Task<byte[]> GetAsync(string key, CancellationToken token = default)
2024-02-03 20:53:32 +01:00
{
byte[] value = null;
2024-02-03 20:53:32 +01:00
if (!string.IsNullOrEmpty(key))
2024-02-03 20:53:32 +01:00
{
value = await memoryCache.GetAsync(key, token).ConfigureAwait(false);
if (value == null)
2024-02-03 20:53:32 +01:00
{
var file = GetFile(key);
try
2024-02-03 20:53:32 +01:00
{
if (file != null && file.Exists && file.CreationTime > DateTime.Now && !token.IsCancellationRequested)
{
value = await ReadAllBytes(file, token).ConfigureAwait(false);
var options = new DistributedCacheEntryOptions { AbsoluteExpiration = file.CreationTime };
await memoryCache.SetAsync(key, value, options, token).ConfigureAwait(false);
2025-05-08 19:51:31 +02:00
2025-08-22 11:06:37 +02:00
logger?.LogDebug("Read {name}", file.FullName);
}
}
catch (Exception ex)
{
2025-03-30 16:35:10 +02:00
logger?.LogError(ex, "Failed reading {name}", file.FullName);
2024-02-03 20:53:32 +01:00
}
}
2024-02-03 20:53:32 +01:00
}
return value;
2024-02-03 20:53:32 +01:00
}
public void Set(string key, byte[] value, DistributedCacheEntryOptions options)
2024-02-03 20:53:32 +01:00
{
if (!string.IsNullOrEmpty(key) && value != null && options != null)
{
memoryCache.Set(key, value, options);
2024-02-05 14:50:30 +01:00
var file = GetFile(key);
2024-02-03 20:53:32 +01:00
try
{
if (file != null && value?.Length > 0)
2024-02-05 14:50:30 +01:00
{
file.Directory.Create();
2025-02-20 11:45:45 +01:00
using (var stream = file.Create())
{
stream.Write(value, 0, value.Length);
}
SetExpiration(file, options);
2025-05-08 19:51:31 +02:00
2025-08-22 11:06:37 +02:00
logger?.LogDebug("Wrote {name}", file.FullName);
}
}
catch (Exception ex)
{
2025-03-30 16:35:10 +02:00
logger?.LogError(ex, "Failed writing {name}", file.FullName);
2024-02-03 20:53:32 +01:00
}
}
2024-02-03 20:53:32 +01:00
}
public async Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options, CancellationToken token = default)
2024-02-03 20:53:32 +01:00
{
if (!string.IsNullOrEmpty(key) && value != null && options != null)
{
await memoryCache.SetAsync(key, value, options, token).ConfigureAwait(false);
2024-02-05 14:50:30 +01:00
var file = GetFile(key);
2024-02-03 20:53:32 +01:00
try
2024-02-03 20:53:32 +01:00
{
if (file != null && value?.Length > 0 && !token.IsCancellationRequested)
2024-02-03 20:53:32 +01:00
{
file.Directory.Create();
using (var stream = file.Create())
{
await stream.WriteAsync(value, 0, value.Length, token).ConfigureAwait(false);
}
2025-02-20 11:45:45 +01:00
SetExpiration(file, options);
2025-05-08 19:51:31 +02:00
2025-08-22 11:06:37 +02:00
logger?.LogDebug("Wrote {name}", file.FullName);
}
}
catch (Exception ex)
{
2025-03-30 16:35:10 +02:00
logger?.LogError(ex, "Failed writing {name}", file.FullName);
2024-02-03 20:53:32 +01:00
}
}
}
public void Refresh(string key)
{
if (!string.IsNullOrEmpty(key))
{
memoryCache.Refresh(key);
}
2024-02-03 20:53:32 +01:00
}
public async Task RefreshAsync(string key, CancellationToken token = default)
2024-02-03 20:53:32 +01:00
{
if (!string.IsNullOrEmpty(key))
{
await memoryCache.RefreshAsync(key, token);
}
2024-02-03 20:53:32 +01:00
}
public void Remove(string key)
{
if (!string.IsNullOrEmpty(key))
{
memoryCache.Remove(key);
var file = GetFile(key);
2024-02-03 20:53:32 +01:00
try
{
if (file != null && file.Exists)
{
file.Delete();
}
}
catch (Exception ex)
2024-02-03 20:53:32 +01:00
{
2025-03-30 16:35:10 +02:00
logger?.LogError(ex, "Failed deleting {name}", file.FullName);
2024-02-03 20:53:32 +01:00
}
}
}
public async Task RemoveAsync(string key, CancellationToken token = default)
2024-02-03 20:53:32 +01:00
{
if (!string.IsNullOrEmpty(key))
{
await memoryCache.RemoveAsync(key, token);
2024-02-05 14:50:30 +01:00
var file = GetFile(key);
2024-02-05 14:50:30 +01:00
try
2024-02-05 14:50:30 +01:00
{
if (file != null && file.Exists && !token.IsCancellationRequested)
{
file.Delete();
}
}
catch (Exception ex)
{
2025-03-30 16:35:10 +02:00
logger?.LogError(ex, "Failed deleting {name}", file.FullName);
2024-02-05 14:50:30 +01:00
}
}
2024-02-03 20:53:32 +01:00
}
2025-02-20 20:29:49 +01:00
public void DeleteExpiredItems()
2021-06-30 20:59:38 +02:00
{
2025-02-20 20:29:49 +01:00
if (!scanningExpiration)
2021-07-02 11:35:20 +02:00
{
2025-02-20 20:29:49 +01:00
scanningExpiration = true;
foreach (var directory in rootDirectory.EnumerateDirectories())
{
2025-02-20 20:29:49 +01:00
var deletedFileCount = ScanDirectory(directory);
if (deletedFileCount > 0)
{
2025-03-30 16:35:10 +02:00
logger?.LogInformation("Deleted {count} expired items in {name}", deletedFileCount, directory.FullName);
}
}
2025-02-20 20:29:49 +01:00
scanningExpiration = false;
2021-07-02 11:35:20 +02:00
}
2021-06-30 20:59:38 +02:00
}
2025-03-30 16:35:10 +02:00
private int ScanDirectory(DirectoryInfo directory)
{
var deletedFileCount = 0;
try
{
deletedFileCount = directory.EnumerateDirectories().Sum(ScanDirectory);
foreach (var file in directory.EnumerateFiles()
2025-11-20 23:53:08 +01:00
.Where(file => file.CreationTime > file.LastWriteTime &&
file.CreationTime <= DateTime.Now))
2025-03-30 16:35:10 +02:00
{
file.Delete();
deletedFileCount++;
}
if (!directory.EnumerateFileSystemInfos().Any())
{
directory.Delete();
}
}
catch (Exception ex)
{
logger?.LogError(ex, "Failed cleaning {name}", directory.FullName);
}
return deletedFileCount;
}
private FileInfo GetFile(string key)
{
2025-09-11 18:11:57 +02:00
FileInfo file = null;
try
{
2025-09-11 18:11:57 +02:00
file = new FileInfo(Path.Combine(rootDirectory.FullName, Path.Combine(key.Split('/'))));
}
catch (Exception ex)
{
2025-03-30 16:35:10 +02:00
logger?.LogError(ex, "Invalid key {key}", key);
}
2025-09-11 18:11:57 +02:00
return file;
}
2025-02-20 20:29:49 +01:00
private static byte[] ReadAllBytes(FileInfo file)
{
2025-11-18 22:23:38 +01:00
using var stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.Read);
2025-09-14 21:02:21 +02:00
var buffer = new byte[stream.Length];
var offset = 0;
2025-02-20 20:29:49 +01:00
2025-09-14 21:02:21 +02:00
while (offset < buffer.Length)
{
offset += stream.Read(buffer, offset, buffer.Length - offset);
2025-02-20 20:29:49 +01:00
}
2025-09-14 21:02:21 +02:00
return buffer;
2025-02-20 20:29:49 +01:00
}
private static async Task<byte[]> ReadAllBytes(FileInfo file, CancellationToken token)
{
2025-11-18 22:23:38 +01:00
using var stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.Read);
2025-09-14 21:02:21 +02:00
var buffer = new byte[stream.Length];
var offset = 0;
2025-02-20 20:29:49 +01:00
2025-09-14 21:02:21 +02:00
while (offset < buffer.Length)
{
offset += await stream.ReadAsync(buffer, offset, buffer.Length - offset, token).ConfigureAwait(false);
2025-02-20 20:29:49 +01:00
}
2025-09-14 21:02:21 +02:00
return buffer;
2025-02-20 20:29:49 +01:00
}
2025-02-20 11:45:45 +01:00
private static void SetExpiration(FileInfo file, DistributedCacheEntryOptions options)
2021-06-30 20:59:38 +02:00
{
2025-02-20 11:45:45 +01:00
file.CreationTime = options.AbsoluteExpiration.HasValue
? options.AbsoluteExpiration.Value.LocalDateTime
2025-02-24 00:23:25 +01:00
: DateTime.Now.Add(options.AbsoluteExpirationRelativeToNow ?? options.SlidingExpiration ?? TimeSpan.FromDays(1));
2021-07-02 11:35:20 +02:00
}
2021-06-30 17:56:02 +02:00
}
}