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

315 lines
9.7 KiB
C#
Raw Normal View History

2025-02-27 18:46:32 +01:00
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;
2021-06-30 17:56:02 +02:00
using System;
using System.Diagnostics;
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
{
/// <summary>
2024-02-03 20:53:32 +01:00
/// IDistributedCache implementation based on local image files.
2021-06-30 17:56:02 +02:00
/// </summary>
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;
private bool scanningExpiration;
2021-06-30 17:56:02 +02:00
2024-08-15 19:46:14 +02:00
public ImageFileCache(string path)
: this(path, TimeSpan.FromHours(1))
{
}
2025-02-20 20:29:49 +01:00
public ImageFileCache(string path, TimeSpan expirationScanFrequency)
2021-06-30 17:56:02 +02:00
{
2024-08-15 19:46:14 +02:00
if (string.IsNullOrEmpty(path))
2021-06-30 17:56:02 +02:00
{
2024-08-15 19:46:14 +02:00
throw new ArgumentException($"The {nameof(path)} argument must not be null or empty.", nameof(path));
2021-06-30 17:56:02 +02:00
}
rootDirectory = new DirectoryInfo(path);
2025-02-20 11:45:45 +01:00
rootDirectory.Create();
2021-07-01 15:43:52 +02:00
Debug.WriteLine($"{nameof(ImageFileCache)}: {rootDirectory.FullName}");
2025-02-20 20:29:49 +01:00
var options = new MemoryDistributedCacheOptions();
if (expirationScanFrequency > TimeSpan.Zero)
{
2025-02-20 20:29:49 +01:00
options.ExpirationScanFrequency = expirationScanFrequency;
expirationScanTimer = new Timer(_ => DeleteExpiredItems(), null, TimeSpan.Zero, expirationScanFrequency);
}
2025-02-20 20:29:49 +01:00
memoryCache = new MemoryDistributedCache(Options.Create(options));
}
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)
{
var buffer = memoryCache.Get(key);
2024-02-03 20:53:32 +01:00
if (buffer == 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)
{
2025-02-20 20:29:49 +01:00
buffer = ReadAllBytes(file);
var options = new DistributedCacheEntryOptions { AbsoluteExpiration = file.CreationTime };
memoryCache.Set(key, buffer, options);
}
}
catch (Exception ex)
{
Debug.WriteLine($"{nameof(ImageFileCache)}: Failed reading {file.FullName}: {ex.Message}");
2024-02-03 20:53:32 +01:00
}
}
return buffer;
}
public async Task<byte[]> GetAsync(string key, CancellationToken token = default)
2024-02-03 20:53:32 +01:00
{
var buffer = await memoryCache.GetAsync(key, token).ConfigureAwait(false);
2024-02-03 20:53:32 +01:00
2024-02-05 16:59:00 +01:00
if (buffer == null)
2024-02-03 20:53:32 +01:00
{
var file = GetFile(key);
try
2024-02-03 20:53:32 +01:00
{
2025-02-20 12:33:58 +01:00
if (file != null && file.Exists && file.CreationTime > DateTime.Now && !token.IsCancellationRequested)
2024-02-03 20:53:32 +01:00
{
2025-02-20 20:29:49 +01:00
buffer = await ReadAllBytes(file, token).ConfigureAwait(false);
var options = new DistributedCacheEntryOptions { AbsoluteExpiration = file.CreationTime };
await memoryCache.SetAsync(key, buffer, options, token).ConfigureAwait(false);
2024-02-03 20:53:32 +01:00
}
}
catch (Exception ex)
{
2025-02-20 20:29:49 +01:00
buffer = null;
Debug.WriteLine($"{nameof(ImageFileCache)}: Failed reading {file.FullName}: {ex.Message}");
}
2024-02-03 20:53:32 +01:00
}
return buffer;
}
public void Set(string key, byte[] buffer, DistributedCacheEntryOptions options)
{
2024-02-05 14:50:30 +01:00
memoryCache.Set(key, buffer, options);
var file = GetFile(key);
2024-02-03 20:53:32 +01:00
try
2024-02-03 20:53:32 +01:00
{
if (file != null && buffer?.Length > 0)
{
2025-02-20 11:45:45 +01:00
file.Directory.Create();
using (var stream = file.Create())
2024-02-05 14:50:30 +01:00
{
2024-08-23 23:05:34 +02:00
stream.Write(buffer, 0, buffer.Length);
2024-02-03 20:53:32 +01:00
}
2025-02-20 11:45:45 +01:00
SetExpiration(file, options);
2024-02-03 20:53:32 +01:00
}
}
catch (Exception ex)
{
Debug.WriteLine($"{nameof(ImageFileCache)}: Failed writing {file.FullName}: {ex.Message}");
}
2024-02-03 20:53:32 +01:00
}
public async Task SetAsync(string key, byte[] buffer, DistributedCacheEntryOptions options, CancellationToken token = default)
2024-02-03 20:53:32 +01:00
{
await memoryCache.SetAsync(key, buffer, options, token).ConfigureAwait(false);
2024-02-05 14:50:30 +01:00
var file = GetFile(key);
2024-02-03 20:53:32 +01:00
2024-08-23 23:05:34 +02:00
try
2024-02-03 20:53:32 +01:00
{
if (file != null && buffer?.Length > 0 && !token.IsCancellationRequested)
2024-02-03 20:53:32 +01:00
{
2025-02-20 11:45:45 +01:00
file.Directory.Create();
using (var stream = file.Create())
2024-02-03 20:53:32 +01:00
{
await stream.WriteAsync(buffer, 0, buffer.Length, token).ConfigureAwait(false);
2024-02-03 20:53:32 +01:00
}
2025-02-20 11:45:45 +01:00
SetExpiration(file, options);
2024-02-03 20:53:32 +01:00
}
2024-08-23 23:05:34 +02:00
}
catch (Exception ex)
{
Debug.WriteLine($"{nameof(ImageFileCache)}: Failed writing {file.FullName}: {ex.Message}");
2024-02-03 20:53:32 +01:00
}
}
public void Refresh(string key)
{
memoryCache.Refresh(key);
2024-02-03 20:53:32 +01:00
}
public Task RefreshAsync(string key, CancellationToken token = default)
{
return memoryCache.RefreshAsync(key, token);
2024-02-03 20:53:32 +01:00
}
public void Remove(string key)
{
memoryCache.Remove(key);
var file = GetFile(key);
2024-02-03 20:53:32 +01:00
try
{
if (file != null && file.Exists)
2024-02-03 20:53:32 +01:00
{
file.Delete();
2024-02-03 20:53:32 +01:00
}
}
catch (Exception ex)
{
Debug.WriteLine($"{nameof(ImageFileCache)}: Failed deleting {file.FullName}: {ex.Message}");
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
{
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
{
if (file != null && file.Exists && !token.IsCancellationRequested)
2024-02-05 14:50:30 +01:00
{
file.Delete();
2024-02-05 14:50:30 +01:00
}
}
catch (Exception ex)
{
Debug.WriteLine($"{nameof(ImageFileCache)}: Failed deleting {file.FullName}: {ex.Message}");
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-02-20 20:29:49 +01:00
Debug.WriteLine($"{nameof(ImageFileCache)}: Deleted {deletedFileCount} expired items in {directory.Name}.");
}
}
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
}
private FileInfo GetFile(string key)
{
try
{
return new FileInfo(Path.Combine(rootDirectory.FullName, Path.Combine(key.Split('/'))));
}
catch (Exception ex)
{
2024-08-31 16:39:49 +02:00
Debug.WriteLine($"{nameof(ImageFileCache)}: Invalid key {key}: {ex.Message}");
}
return null;
}
2025-02-20 20:29:49 +01:00
private static byte[] ReadAllBytes(FileInfo file)
{
using (var stream = file.OpenRead())
{
var buffer = new byte[stream.Length];
var offset = 0;
while (offset < buffer.Length)
{
offset += stream.Read(buffer, offset, buffer.Length - offset);
}
return buffer;
}
}
private static async Task<byte[]> ReadAllBytes(FileInfo file, CancellationToken token)
{
using (var stream = file.OpenRead())
{
var buffer = new byte[stream.Length];
var offset = 0;
while (offset < buffer.Length)
{
offset += await stream.ReadAsync(buffer, offset, buffer.Length - offset, token).ConfigureAwait(false);
}
return buffer;
}
}
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
}
2025-02-20 20:29:49 +01:00
private static int ScanDirectory(DirectoryInfo directory)
2021-07-02 11:35:20 +02:00
{
var deletedFileCount = 0;
try
2021-07-02 11:35:20 +02:00
{
2025-02-20 20:29:49 +01:00
deletedFileCount = directory.EnumerateDirectories().Sum(ScanDirectory);
2024-02-11 16:17:35 +01:00
foreach (var file in directory.EnumerateFiles().Where(f => f.CreationTime <= DateTime.Now))
2021-06-30 20:59:38 +02:00
{
file.Delete();
deletedFileCount++;
2021-06-30 20:59:38 +02:00
}
if (!directory.EnumerateFileSystemInfos().Any())
2021-06-30 20:59:38 +02:00
{
directory.Delete();
2021-06-30 20:59:38 +02:00
}
2024-02-11 16:17:35 +01:00
}
catch (Exception ex)
2024-02-11 16:17:35 +01:00
{
Debug.WriteLine($"{nameof(ImageFileCache)}: Failed cleaning {directory.FullName}: {ex.Message}");
2021-06-30 17:56:02 +02:00
}
return deletedFileCount;
}
2021-06-30 17:56:02 +02:00
}
}