XAML-Map-Control/Caches/FileDbCache/FileDbCache.cs

207 lines
6.3 KiB
C#
Raw Permalink Normal View History

2025-02-27 18:46:32 +01:00
using FileDbNs;
2024-02-03 20:53:32 +01:00
using Microsoft.Extensions.Caching.Distributed;
2025-03-30 16:35:10 +02:00
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
2024-02-03 20:53:32 +01:00
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace MapControl.Caching
{
2025-03-30 16:35:10 +02:00
public class FileDbCacheOptions : IOptions<FileDbCacheOptions>
{
public FileDbCacheOptions Value => this;
public string Path { get; set; }
public TimeSpan ExpirationScanFrequency { get; set; } = TimeSpan.FromHours(1);
}
2024-02-03 20:53:32 +01:00
/// <summary>
2025-02-25 18:19:57 +01:00
/// IDistributedCache implementation based on FileDb, https://github.com/eztools-software/FileDb.
2024-02-03 20:53:32 +01:00
/// </summary>
2024-08-20 17:59:36 +02:00
public sealed class FileDbCache : IDistributedCache, IDisposable
2024-02-03 20:53:32 +01:00
{
2025-12-05 15:07:01 +01:00
private const string KeyField = "Key";
private const string ValueField = "Value";
private const string ExpiresField = "Expires";
2024-02-03 20:53:32 +01:00
private readonly FileDb fileDb = new FileDb { AutoFlush = true };
2025-02-24 20:19:27 +01:00
private readonly Timer timer;
2025-03-30 16:35:10 +02:00
private readonly ILogger logger;
public FileDbCache(string path, ILoggerFactory loggerFactory = null)
: this(new FileDbCacheOptions { Path = path }, loggerFactory)
{
}
2024-02-03 20:53:32 +01:00
2025-03-30 16:35:10 +02:00
public FileDbCache(IOptions<FileDbCacheOptions> optionsAccessor, ILoggerFactory loggerFactory = null)
: this(optionsAccessor.Value, loggerFactory)
2025-02-19 19:34:08 +01:00
{
}
2025-03-30 16:35:10 +02:00
public FileDbCache(FileDbCacheOptions options, ILoggerFactory loggerFactory = null)
2024-02-03 20:53:32 +01:00
{
2025-03-30 16:35:10 +02:00
var path = options.Path;
if (string.IsNullOrEmpty(path) || string.IsNullOrEmpty(Path.GetExtension(path)))
2024-02-03 20:53:32 +01:00
{
path = Path.Combine(path ?? "", "TileCache.fdb");
2024-02-03 20:53:32 +01:00
}
2025-03-31 20:55:57 +02:00
logger = loggerFactory?.CreateLogger<FileDbCache>();
2024-02-03 20:53:32 +01:00
try
{
fileDb.Open(path);
2025-02-20 20:29:49 +01:00
2025-03-30 16:35:10 +02:00
logger?.LogInformation("Opened database {path}", path);
2024-02-03 20:53:32 +01:00
}
catch
{
if (File.Exists(path))
{
File.Delete(path);
}
else
{
Directory.CreateDirectory(Path.GetDirectoryName(path));
}
fileDb.Create(path, new Field[]
{
2025-12-05 15:07:01 +01:00
new Field(KeyField, DataTypeEnum.String) { IsPrimaryKey = true },
new Field(ValueField, DataTypeEnum.Byte) { IsArray = true },
new Field(ExpiresField, DataTypeEnum.DateTime)
2024-02-03 20:53:32 +01:00
});
2025-03-30 16:35:10 +02:00
logger?.LogInformation("Created database {path}", path);
2024-02-03 20:53:32 +01:00
}
2025-02-19 19:34:08 +01:00
2025-03-30 16:35:10 +02:00
if (options.ExpirationScanFrequency > TimeSpan.Zero)
2025-02-19 19:34:08 +01:00
{
2025-03-30 16:35:10 +02:00
timer = new Timer(_ => DeleteExpiredItems(), null, TimeSpan.Zero, options.ExpirationScanFrequency);
2025-02-19 19:34:08 +01:00
}
2024-02-03 20:53:32 +01:00
}
public void Dispose()
{
2025-02-24 20:19:27 +01:00
timer?.Dispose();
2024-02-03 20:53:32 +01:00
fileDb.Dispose();
}
public byte[] Get(string key)
{
byte[] value = null;
if (!string.IsNullOrEmpty(key))
2024-02-03 20:53:32 +01:00
{
try
{
2025-12-05 15:07:01 +01:00
var record = fileDb.GetRecordByKey(key, new string[] { ValueField, ExpiresField }, false);
2025-02-24 18:34:41 +01:00
if (record != null && (DateTime)record[1] > DateTime.UtcNow)
{
value = (byte[])record[0];
}
}
catch (Exception ex)
2025-02-24 20:19:27 +01:00
{
2025-03-30 16:35:10 +02:00
logger?.LogError(ex, "Get({key})", key);
2024-02-03 20:53:32 +01:00
}
}
return value;
}
2025-02-28 15:40:41 +01:00
public Task<byte[]> GetAsync(string key, CancellationToken token = default)
{
return Task.FromResult(Get(key));
}
2024-02-03 20:53:32 +01:00
public void Set(string key, byte[] value, DistributedCacheEntryOptions options)
{
if (!string.IsNullOrEmpty(key) && value != null && options != null)
2024-02-03 20:53:32 +01:00
{
var expiration = options.AbsoluteExpiration.HasValue
? options.AbsoluteExpiration.Value.UtcDateTime
: DateTime.UtcNow.Add(options.AbsoluteExpirationRelativeToNow ?? options.SlidingExpiration ?? TimeSpan.FromDays(1));
2024-02-03 20:53:32 +01:00
var fieldValues = new FieldValues(3)
2025-02-24 20:19:27 +01:00
{
2025-12-05 15:07:01 +01:00
{ ValueField, value },
{ ExpiresField, expiration }
};
try
{
if (fileDb.GetRecordByKey(key, new string[0], false) != null)
{
fileDb.UpdateRecordByKey(key, fieldValues);
}
else
{
2025-12-05 15:07:01 +01:00
fieldValues.Add(KeyField, key);
fileDb.AddRecord(fieldValues);
}
2025-02-24 20:19:27 +01:00
}
catch (Exception ex)
2024-02-03 20:53:32 +01:00
{
2025-03-30 16:35:10 +02:00
logger?.LogError(ex, "Set({key})", key);
2024-02-03 20:53:32 +01:00
}
}
}
2025-02-28 15:40:41 +01:00
public Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options, CancellationToken token = default)
{
Set(key, value, options);
return Task.CompletedTask;
}
2024-02-03 20:53:32 +01:00
public void Refresh(string key)
{
2025-02-28 15:40:41 +01:00
}
public Task RefreshAsync(string key, CancellationToken token = default)
{
return Task.CompletedTask;
2024-02-03 20:53:32 +01:00
}
public void Remove(string key)
{
if (!string.IsNullOrEmpty(key))
2024-02-03 20:53:32 +01:00
{
try
{
fileDb.DeleteRecordByKey(key);
}
catch (Exception ex)
{
2025-03-30 16:35:10 +02:00
logger?.LogError(ex, "Remove({key})", key);
}
2024-02-03 20:53:32 +01:00
}
}
2025-02-28 15:40:41 +01:00
public Task RemoveAsync(string key, CancellationToken token = default)
{
Remove(key);
return Task.CompletedTask;
}
2025-02-20 20:29:49 +01:00
public void DeleteExpiredItems()
{
2025-12-05 15:07:01 +01:00
var deletedItemsCount = fileDb.DeleteRecords(new FilterExpression(ExpiresField, DateTime.UtcNow, ComparisonOperatorEnum.LessThanOrEqual));
2025-02-24 18:34:41 +01:00
2025-03-30 16:35:10 +02:00
if (deletedItemsCount > 0)
2025-02-24 20:19:27 +01:00
{
fileDb.Clean();
2025-02-24 18:34:41 +01:00
2025-03-30 16:35:10 +02:00
logger?.LogInformation("Deleted {count} expired items", deletedItemsCount);
}
}
2024-02-03 20:53:32 +01:00
}
}