summary refs log tree commit diff
path: root/extra/admin-api/Interop/Spacebar.Interop.Cdn.Abstractions/LruFileCache.cs
blob: 3bd4ec09556d37e35d2e5712cdb0fa3fd750dfa9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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; }
    }
}