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

231 lines
6.8 KiB
C#
Raw Normal View History

2024-02-03 20:53:32 +01:00
// XAML Map Control - https://github.com/ClemensFischer/XAML-Map-Control
2025-01-01 18:57:55 +01:00
// Copyright © Clemens Fischer
2024-02-03 20:53:32 +01:00
// Licensed under the Microsoft Public License (Ms-PL)
using FileDbNs;
using Microsoft.Extensions.Caching.Distributed;
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace MapControl.Caching
{
/// <summary>
/// IDistributedCache implementation based on FileDb, a free and simple No-SQL database by EzTools Software.
/// See http://www.eztools-software.com/tools/filedb/.
/// </summary>
2024-08-20 17:59:36 +02:00
public sealed class FileDbCache : IDistributedCache, IDisposable
2024-02-03 20:53:32 +01:00
{
private const string keyField = "Key";
private const string valueField = "Value";
private const string expiresField = "Expires";
private readonly FileDb fileDb = new FileDb { AutoFlush = true };
2025-02-20 20:29:49 +01:00
private readonly Timer expirationScanTimer;
2024-02-03 20:53:32 +01:00
public FileDbCache(string path)
2025-02-19 19:34:08 +01:00
: this(path, TimeSpan.FromHours(1))
{
}
2025-02-20 20:29:49 +01:00
public FileDbCache(string path, TimeSpan expirationScanFrequency)
2024-02-03 20:53:32 +01:00
{
if (string.IsNullOrEmpty(path))
{
2024-02-05 15:51:39 +01:00
throw new ArgumentException($"The {nameof(path)} argument must not be null or empty.", nameof(path));
2024-02-03 20:53:32 +01:00
}
if (string.IsNullOrEmpty(Path.GetExtension(path)))
{
path = Path.Combine(path, "TileCache.fdb");
}
try
{
fileDb.Open(path);
2025-02-20 20:29:49 +01:00
2024-08-31 16:39:49 +02:00
Debug.WriteLine($"{nameof(FileDbCache)}: Opened database {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[]
{
new Field(keyField, DataTypeEnum.String) { IsPrimaryKey = true },
new Field(valueField, DataTypeEnum.Byte) { IsArray = true },
new Field(expiresField, DataTypeEnum.DateTime)
});
2024-08-31 16:39:49 +02:00
Debug.WriteLine($"{nameof(FileDbCache)}: Created database {path}");
2024-02-03 20:53:32 +01:00
}
2025-02-19 19:34:08 +01:00
2025-02-20 20:29:49 +01:00
if (expirationScanFrequency > TimeSpan.Zero)
2025-02-19 19:34:08 +01:00
{
2025-02-20 20:29:49 +01:00
expirationScanTimer = new Timer(_ => DeleteExpiredItems(), null, TimeSpan.Zero, expirationScanFrequency);
2025-02-19 19:34:08 +01:00
}
2024-02-03 20:53:32 +01:00
}
public void Dispose()
{
2025-02-20 20:29:49 +01:00
expirationScanTimer?.Dispose();
2024-02-03 20:53:32 +01:00
fileDb.Dispose();
}
public byte[] Get(string key)
{
2024-02-05 16:33:14 +01:00
CheckArgument(key);
2024-02-05 15:51:39 +01:00
2024-02-03 20:53:32 +01:00
byte[] value = null;
try
{
2025-02-24 18:34:41 +01:00
lock (fileDb)
2024-02-03 20:53:32 +01:00
{
2025-02-24 18:34:41 +01:00
var record = fileDb.GetRecordByKey(key, new string[] { valueField, expiresField }, false);
if (record != null && (DateTime)record[1] > DateTime.UtcNow)
{
value = (byte[])record[0];
}
2024-02-03 20:53:32 +01:00
}
}
catch (Exception ex)
{
2024-08-31 16:39:49 +02:00
Debug.WriteLine($"{nameof(FileDbCache)}.Get({key}): {ex.Message}");
2024-02-03 20:53:32 +01:00
}
return value;
}
public void Set(string key, byte[] value, DistributedCacheEntryOptions options)
{
2024-02-05 16:33:14 +01:00
CheckArguments(key, value, options);
2024-02-05 15:51:39 +01:00
2025-02-20 20:29:49 +01:00
var expiration = options.AbsoluteExpiration.HasValue
2025-02-20 21:41:28 +01:00
? options.AbsoluteExpiration.Value.UtcDateTime
2025-02-24 00:23:18 +01:00
: DateTime.UtcNow.Add(options.AbsoluteExpirationRelativeToNow ?? options.SlidingExpiration ?? TimeSpan.FromDays(1));
2024-02-03 20:53:32 +01:00
var fieldValues = new FieldValues(3)
{
2024-02-05 15:51:39 +01:00
{ valueField, value },
2024-02-03 20:53:32 +01:00
{ expiresField, expiration }
};
try
{
2025-02-24 18:34:41 +01:00
lock (fileDb)
2024-02-03 20:53:32 +01:00
{
2025-02-24 18:34:41 +01:00
if (fileDb.GetRecordByKey(key, new string[0], false) != null)
{
fileDb.UpdateRecordByKey(key, fieldValues);
}
else
{
fieldValues.Add(keyField, key);
fileDb.AddRecord(fieldValues);
}
2024-02-03 20:53:32 +01:00
}
}
catch (Exception ex)
{
2024-08-31 16:39:49 +02:00
Debug.WriteLine($"{nameof(FileDbCache)}.Set({key}): {ex.Message}");
2024-02-03 20:53:32 +01:00
}
}
public void Refresh(string key)
{
}
public void Remove(string key)
{
2024-02-05 16:33:14 +01:00
CheckArgument(key);
2024-02-05 15:51:39 +01:00
2024-02-03 20:53:32 +01:00
try
{
2025-02-24 18:34:41 +01:00
lock (fileDb)
{
fileDb.DeleteRecordByKey(key);
}
2024-02-03 20:53:32 +01:00
}
catch (Exception ex)
{
2024-08-31 16:39:49 +02:00
Debug.WriteLine($"{nameof(FileDbCache)}.Remove({key}): {ex.Message}");
2024-02-03 20:53:32 +01:00
}
}
2025-02-20 20:29:49 +01:00
public void DeleteExpiredItems()
{
2025-02-24 18:34:41 +01:00
lock (fileDb)
{
2025-02-24 18:34:41 +01:00
var deleted = fileDb.DeleteRecords(new FilterExpression(expiresField, DateTime.UtcNow, ComparisonOperatorEnum.LessThanOrEqual));
if (deleted > 0)
{
fileDb.Clean();
Debug.WriteLine($"{nameof(FileDbCache)}: Deleted {deleted} expired items");
}
}
}
2024-02-05 15:51:39 +01:00
public Task<byte[]> GetAsync(string key, CancellationToken token = default)
2024-02-03 20:53:32 +01:00
{
2024-02-05 15:51:39 +01:00
return Task.FromResult(Get(key));
}
public Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options, CancellationToken token = default)
{
Set(key, value, options);
2024-08-31 11:55:59 +02:00
2024-02-03 20:53:32 +01:00
return Task.CompletedTask;
}
2024-02-05 15:51:39 +01:00
public Task RefreshAsync(string key, CancellationToken token = default)
2024-02-03 20:53:32 +01:00
{
2024-02-05 15:51:39 +01:00
Refresh(key);
2024-08-31 11:55:59 +02:00
2024-02-05 15:51:39 +01:00
return Task.CompletedTask;
}
2024-02-03 20:53:32 +01:00
2024-02-05 15:51:39 +01:00
public Task RemoveAsync(string key, CancellationToken token = default)
{
Remove(key);
2024-08-31 11:55:59 +02:00
2024-02-05 15:51:39 +01:00
return Task.CompletedTask;
2024-02-03 20:53:32 +01:00
}
2024-02-05 16:33:14 +01:00
private static void CheckArgument(string key)
{
if (string.IsNullOrEmpty(key))
{
throw new ArgumentException($"The {nameof(key)} argument must not be null or empty.", nameof(key));
}
}
private static void CheckArguments(string key, byte[] value, DistributedCacheEntryOptions options)
{
CheckArgument(key);
if (value == null)
{
throw new ArgumentNullException($"The {nameof(value)} argument must not be null.", nameof(value));
}
if (options == null)
{
throw new ArgumentNullException($"The {nameof(options)} argument must not be null.", nameof(options));
}
}
2024-02-03 20:53:32 +01:00
}
}