summary refs log tree commit diff
path: root/extra/admin-api/Interop/Spacebar.Interop.Cdn.Abstractions/LruFileCache.cs
diff options
context:
space:
mode:
Diffstat (limited to 'extra/admin-api/Interop/Spacebar.Interop.Cdn.Abstractions/LruFileCache.cs')
-rw-r--r--extra/admin-api/Interop/Spacebar.Interop.Cdn.Abstractions/LruFileCache.cs35
1 files changed, 35 insertions, 0 deletions
diff --git a/extra/admin-api/Interop/Spacebar.Interop.Cdn.Abstractions/LruFileCache.cs b/extra/admin-api/Interop/Spacebar.Interop.Cdn.Abstractions/LruFileCache.cs
new file mode 100644

index 00000000..3bd4ec09 --- /dev/null +++ b/extra/admin-api/Interop/Spacebar.Interop.Cdn.Abstractions/LruFileCache.cs
@@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace Spacebar.Interop.Cdn.Abstractions; + +public class LruFileCache(int maxSizeBytes) { + private readonly Dictionary<string, Entry> _entries = new(); + + public async Task<Entry?> GetOrAdd(string key, Func<Task<Entry>> factory) { + if (_entries.TryGetValue(key, out var entry)) { + entry.LastAccessed = DateTimeOffset.UtcNow; + return entry; + } + + entry = await factory(); + if (entry.Data.Length > 0 && entry.Data.Length <= maxSizeBytes) + _entries[key] = entry; + + if (_entries.Sum(kv => kv.Value.Data.Length) > maxSizeBytes) { + var oldestKey = _entries.OrderBy(kv => kv.Value.LastAccessed).First().Key; + _entries.Remove(oldestKey); + } + + return entry; + } + + public class Entry { + public DateTimeOffset LastAccessed { get; set; } + public byte[] Data { get; set; } + public string MimeType { get; set; } + } +} +