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

397 lines
13 KiB
C#
Raw Normal View History

2021-06-30 17:56:02 +02:00
// XAML Map Control - https://github.com/ClemensFischer/XAML-Map-Control
2024-02-03 20:53:32 +01:00
// Copyright © 2024 Clemens Fischer
2021-06-30 17:56:02 +02:00
// Licensed under the Microsoft Public License (Ms-PL)
2024-02-03 20:53: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;
2021-06-30 17:56:02 +02:00
using System.Text;
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 partial class ImageFileCache : IDistributedCache
2021-06-30 17:56:02 +02:00
{
2024-02-11 16:17:35 +01:00
private static readonly byte[] expirationTag = Encoding.ASCII.GetBytes("EXPIRES:");
2021-06-30 17:56:02 +02:00
2024-05-19 23:22:54 +02:00
private readonly MemoryDistributedCache memoryCache = new MemoryDistributedCache(Options.Create(new MemoryDistributedCacheOptions()));
2021-06-30 17:56:02 +02:00
private readonly string rootDirectory;
public ImageFileCache(string directory)
{
if (string.IsNullOrEmpty(directory))
{
2024-02-05 15:29:11 +01:00
throw new ArgumentException($"The {nameof(directory)} argument must not be null or empty.", nameof(directory));
2021-06-30 17:56:02 +02:00
}
rootDirectory = directory;
2021-07-01 15:43:52 +02:00
2024-02-10 23:43:57 +01:00
Debug.WriteLine($"ImageFileCache: {rootDirectory}");
2021-06-30 17:56:02 +02:00
ThreadPool.QueueUserWorkItem(o => Clean());
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 path = GetPath(key);
try
2024-02-03 20:53:32 +01:00
{
if (path != null && File.Exists(path))
{
buffer = File.ReadAllBytes(path);
2024-02-11 16:17:35 +01:00
if (CheckExpiration(ref buffer, out DistributedCacheEntryOptions options))
{
2024-02-11 16:17:35 +01:00
memoryCache.Set(key, buffer, options);
}
}
}
catch (Exception ex)
{
Debug.WriteLine($"ImageFileCache: Failed reading {path}: {ex.Message}");
2024-02-03 20:53:32 +01:00
}
}
return buffer;
}
public async Task<byte[]> GetAsync(string key, CancellationToken token = default)
{
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 path = GetPath(key);
try
2024-02-03 20:53:32 +01:00
{
2024-02-05 16:59:00 +01:00
if (path != null && File.Exists(path) && !token.IsCancellationRequested)
2024-02-03 20:53:32 +01:00
{
buffer = await ReadAllBytesAsync(path).ConfigureAwait(false);
2024-02-11 16:17:35 +01:00
if (CheckExpiration(ref buffer, out DistributedCacheEntryOptions options))
2024-02-03 20:53:32 +01:00
{
2024-02-11 16:17:35 +01:00
await memoryCache.SetAsync(key, buffer, options, token).ConfigureAwait(false);
2024-02-03 20:53:32 +01:00
}
}
}
catch (Exception ex)
{
Debug.WriteLine($"ImageFileCache: Failed reading {path}: {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);
2024-02-03 20:53:32 +01:00
var path = GetPath(key);
2024-02-05 14:50:30 +01:00
if (path != null && buffer?.Length > 0)
2024-02-03 20:53:32 +01:00
{
2024-02-05 14:50:30 +01:00
try
{
2024-02-05 14:50:30 +01:00
Directory.CreateDirectory(Path.GetDirectoryName(path));
2024-02-03 20:53:32 +01:00
2024-02-05 14:50:30 +01:00
using (var stream = File.Create(path))
{
Write(stream, buffer);
2024-02-11 16:17:35 +01:00
if (GetExpirationBytes(options, out byte[] expiration))
2024-02-05 14:50:30 +01:00
{
2024-02-11 16:17:35 +01:00
Write(stream, expiration);
2024-02-03 20:53:32 +01:00
}
}
2024-02-05 14:50:30 +01:00
SetAccessControl(path);
}
catch (Exception ex)
{
Debug.WriteLine($"ImageFileCache: Failed writing {path}: {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-05 14:50:30 +01:00
await memoryCache.SetAsync(key, buffer, options, token).ConfigureAwait(false);
2024-02-03 20:53:32 +01:00
var path = GetPath(key);
2024-02-05 14:50:30 +01:00
if (path != null && buffer?.Length > 0 && !token.IsCancellationRequested)
2024-02-03 20:53:32 +01:00
{
try
{
2024-02-05 14:50:30 +01:00
Directory.CreateDirectory(Path.GetDirectoryName(path));
2024-02-03 20:53:32 +01:00
2024-02-05 14:50:30 +01:00
using (var stream = File.Create(path))
2024-02-03 20:53:32 +01:00
{
2024-02-05 14:50:30 +01:00
await WriteAsync(stream, buffer).ConfigureAwait(false);
2024-02-11 16:17:35 +01:00
if (GetExpirationBytes(options, out byte[] expiration))
2024-02-05 14:50:30 +01:00
{
2024-02-11 16:17:35 +01:00
await WriteAsync(stream, expiration).ConfigureAwait(false);
2024-02-03 20:53:32 +01:00
}
}
2024-02-05 14:50:30 +01:00
SetAccessControl(path);
2024-02-03 20:53:32 +01:00
}
catch (Exception ex)
{
Debug.WriteLine($"ImageFileCache: Failed writing {path}: {ex.Message}");
}
}
}
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);
2024-02-03 20:53:32 +01:00
var path = GetPath(key);
try
{
if (path != null && File.Exists(path))
{
File.Delete(path);
}
}
catch (Exception ex)
{
Debug.WriteLine($"ImageFileCache: Failed deleting {path}: {ex.Message}");
}
}
2024-02-05 14:50:30 +01:00
public async Task RemoveAsync(string key, CancellationToken token = default)
2024-02-03 20:53:32 +01:00
{
2024-02-05 14:50:30 +01:00
await memoryCache.RemoveAsync(key, token);
var path = GetPath(key);
try
{
if (path != null && File.Exists(path) && !token.IsCancellationRequested)
{
File.Delete(path);
}
}
catch (Exception ex)
{
Debug.WriteLine($"ImageFileCache: Failed deleting {path}: {ex.Message}");
}
2024-02-03 20:53:32 +01:00
}
public void Clean()
2021-06-30 20:59:38 +02:00
{
2024-02-10 23:43:57 +01:00
var deletedFileCount = CleanDirectory(new DirectoryInfo(rootDirectory));
2021-07-02 11:35:20 +02:00
2024-02-10 23:43:57 +01:00
if (deletedFileCount > 0)
2021-07-02 11:35:20 +02:00
{
2024-02-10 23:43:57 +01:00
Debug.WriteLine($"ImageFileCache: Deleted {deletedFileCount} expired files.");
2021-07-02 11:35:20 +02:00
}
2021-06-30 20:59:38 +02:00
}
public Task CleanAsync()
{
return Task.Factory.StartNew(Clean, TaskCreationOptions.LongRunning);
}
private string GetPath(string key)
{
try
{
return Path.Combine(rootDirectory, Path.Combine(key.Split('/')));
}
catch (Exception ex)
{
2024-02-10 23:43:57 +01:00
Debug.WriteLine($"ImageFileCache: Invalid key {key}: {ex.Message}");
}
return null;
}
2021-06-30 20:59:38 +02:00
private static int CleanDirectory(DirectoryInfo directory)
{
var deletedFileCount = 0;
2021-07-02 11:35:20 +02:00
try
{
deletedFileCount += directory.EnumerateDirectories().Sum(dir => CleanDirectory(dir));
2021-06-30 20:59:38 +02:00
2021-07-02 11:35:20 +02:00
deletedFileCount += directory.EnumerateFiles().Sum(file => CleanFile(file));
2021-06-30 20:59:38 +02:00
2021-07-02 11:35:20 +02:00
if (!directory.EnumerateFileSystemInfos().Any())
2021-06-30 20:59:38 +02:00
{
directory.Delete();
}
2021-07-02 11:35:20 +02:00
}
catch (Exception ex)
{
Debug.WriteLine($"ImageFileCache: Failed cleaning {directory.FullName}: {ex.Message}");
2021-07-02 11:35:20 +02:00
}
return deletedFileCount;
}
private static int CleanFile(FileInfo file)
{
var deletedFileCount = 0;
2024-02-11 16:17:35 +01:00
if (file.Length > 16)
2021-07-02 11:35:20 +02:00
{
2024-02-11 16:17:35 +01:00
try
{
var hasExpired = false;
var buffer = new byte[16];
2024-02-03 20:53:32 +01:00
2024-02-11 16:17:35 +01:00
using (var stream = file.OpenRead())
{
stream.Seek(-16, SeekOrigin.End);
hasExpired = stream.Read(buffer, 0, 16) == 16
&& GetExpirationTicks(buffer, out long expiration)
&& expiration <= DateTimeOffset.UtcNow.Ticks;
}
if (hasExpired)
{
file.Delete();
deletedFileCount = 1;
}
}
catch (Exception ex)
2021-06-30 20:59:38 +02:00
{
2024-02-11 16:17:35 +01:00
Debug.WriteLine($"ImageFileCache: Failed cleaning {file.FullName}: {ex.Message}");
2021-06-30 20:59:38 +02:00
}
}
return deletedFileCount;
}
2024-02-11 16:17:35 +01:00
private static bool CheckExpiration(ref byte[] buffer, out DistributedCacheEntryOptions options)
2021-06-30 20:59:38 +02:00
{
2024-02-11 16:17:35 +01:00
if (GetExpirationTicks(buffer, out long expiration))
2024-02-03 20:53:32 +01:00
{
2024-02-11 16:17:35 +01:00
if (expiration > DateTimeOffset.UtcNow.Ticks)
2021-06-30 20:59:38 +02:00
{
2024-02-11 16:17:35 +01:00
Array.Resize(ref buffer, buffer.Length - 16);
2021-06-30 20:59:38 +02:00
2024-02-11 16:17:35 +01:00
options = new DistributedCacheEntryOptions
2021-06-30 20:59:38 +02:00
{
2024-02-11 16:17:35 +01:00
AbsoluteExpiration = new DateTimeOffset(expiration, TimeSpan.Zero)
};
return true;
2021-06-30 20:59:38 +02:00
}
2024-02-11 16:17:35 +01:00
buffer = null; // buffer has expired
2021-06-30 20:59:38 +02:00
}
2024-02-11 16:17:35 +01:00
options = null;
return false;
2021-06-30 20:59:38 +02:00
}
2024-02-11 16:17:35 +01:00
private static bool GetExpirationTicks(byte[] buffer, out long expirationTicks)
2021-06-30 17:56:02 +02:00
{
2024-02-11 16:17:35 +01:00
if (buffer.Length >= 16 &&
expirationTag.SequenceEqual(buffer.Skip(buffer.Length - 16).Take(8)))
2021-06-30 17:56:02 +02:00
{
2024-02-11 16:17:35 +01:00
expirationTicks = BitConverter.ToInt64(buffer, buffer.Length - 8);
return true;
2021-06-30 17:56:02 +02:00
}
2024-02-11 16:17:35 +01:00
expirationTicks = 0;
return false;
2021-06-30 17:56:02 +02:00
}
2024-02-11 16:17:35 +01:00
private static bool GetExpirationBytes(DistributedCacheEntryOptions options, out byte[] expirationBytes)
2021-06-30 17:56:02 +02:00
{
2024-02-11 16:17:35 +01:00
long expirationTicks;
2021-06-30 20:59:38 +02:00
2024-02-11 16:17:35 +01:00
if (options.AbsoluteExpiration.HasValue)
2021-06-30 17:56:02 +02:00
{
2024-02-11 16:17:35 +01:00
expirationTicks = options.AbsoluteExpiration.Value.Ticks;
}
else if (options.AbsoluteExpirationRelativeToNow.HasValue)
{
expirationTicks = DateTimeOffset.UtcNow.Add(options.AbsoluteExpirationRelativeToNow.Value).Ticks;
}
else if (options.SlidingExpiration.HasValue)
{
expirationTicks = DateTimeOffset.UtcNow.Add(options.SlidingExpiration.Value).Ticks;
}
else
{
expirationBytes = null;
return false;
2021-06-30 17:56:02 +02:00
}
2024-02-11 16:17:35 +01:00
expirationBytes = expirationTag.Concat(BitConverter.GetBytes(expirationTicks)).ToArray();
return true;
2021-06-30 17:56:02 +02:00
}
#if NETFRAMEWORK
private static async Task<byte[]> ReadAllBytesAsync(string path)
{
using (var stream = File.OpenRead(path))
{
var buffer = new byte[stream.Length];
var offset = 0;
while (offset < buffer.Length)
{
offset += await stream.ReadAsync(buffer, offset, buffer.Length - offset).ConfigureAwait(false);
}
return buffer;
}
}
#else
private static Task<byte[]> ReadAllBytesAsync(string path) => File.ReadAllBytesAsync(path);
#endif
private static void Write(Stream stream, byte[] bytes) => stream.Write(bytes, 0, bytes.Length);
private static Task WriteAsync(Stream stream, byte[] bytes) => stream.WriteAsync(bytes, 0, bytes.Length);
static partial void SetAccessControl(string path);
2024-05-19 23:22:54 +02:00
#if !UWP && !AVALONIA
static partial void SetAccessControl(string path)
{
var fileInfo = new FileInfo(path);
var fileSecurity = fileInfo.GetAccessControl();
2024-05-19 23:22:54 +02:00
var fullControlRule = new System.Security.AccessControl.FileSystemAccessRule(
new System.Security.Principal.SecurityIdentifier(
System.Security.Principal.WellKnownSidType.BuiltinUsersSid, null),
System.Security.AccessControl.FileSystemRights.FullControl,
System.Security.AccessControl.AccessControlType.Allow);
fileSecurity.AddAccessRule(fullControlRule);
fileInfo.SetAccessControl(fileSecurity);
}
#endif
2021-06-30 17:56:02 +02:00
}
}