about summary refs log tree commit diff
path: root/LibMatrix/Homeservers/Extensions/NamedCaches/NamedCache.cs
diff options
context:
space:
mode:
authorRory& <root@rory.gay>2024-03-15 18:10:58 +0100
committerRory& <root@rory.gay>2024-03-15 18:11:18 +0100
commit096375344ef87fe53ca009b7a7eaa34c9c9f5407 (patch)
tree76d666cd6961ca04ae9e91e47c43d91eed27a87a /LibMatrix/Homeservers/Extensions/NamedCaches/NamedCache.cs
parentFix README (diff)
downloadLibMatrix-096375344ef87fe53ca009b7a7eaa34c9c9f5407.tar.xz
Bot changes, move named filters to subclass
Diffstat (limited to 'LibMatrix/Homeservers/Extensions/NamedCaches/NamedCache.cs')
-rw-r--r--LibMatrix/Homeservers/Extensions/NamedCaches/NamedCache.cs37
1 files changed, 37 insertions, 0 deletions
diff --git a/LibMatrix/Homeservers/Extensions/NamedCaches/NamedCache.cs b/LibMatrix/Homeservers/Extensions/NamedCaches/NamedCache.cs
new file mode 100644
index 0000000..622eef6
--- /dev/null
+++ b/LibMatrix/Homeservers/Extensions/NamedCaches/NamedCache.cs
@@ -0,0 +1,37 @@
+namespace LibMatrix.Homeservers.Extensions.NamedCaches;
+
+public class NamedCache<T>(AuthenticatedHomeserverGeneric hs, string name) where T : class {
+    private Dictionary<string, T>? _cache = new();
+    private DateTime _expiry = DateTime.MinValue;
+    
+    public async Task<Dictionary<string, T>> ReadCacheMapAsync() {
+        _cache = await hs.GetAccountDataOrNullAsync<Dictionary<string, T>>(name);
+
+        return _cache ?? new();
+    }
+    
+    public async Task<Dictionary<string,T>> ReadCacheMapCachedAsync() {
+        if (_expiry < DateTime.Now || _cache == null) {
+            _cache = await ReadCacheMapAsync();
+            _expiry = DateTime.Now.AddMinutes(5);
+        }
+
+        return _cache;
+    }
+    
+    public virtual async Task<T?> GetValueAsync(string key) {
+        return (await ReadCacheMapCachedAsync()).GetValueOrDefault(key);
+    }
+    
+    public virtual async Task<T> SetValueAsync(string key, T value) {
+        var cache = await ReadCacheMapCachedAsync();
+        cache[key] = value;
+        await hs.SetAccountDataAsync(name, cache);
+
+        return value;
+    }
+    
+    public virtual async Task<T> GetOrSetValueAsync(string key, Func<Task<T>> value) {
+        return (await ReadCacheMapCachedAsync()).GetValueOrDefault(key) ?? await SetValueAsync(key, await value());
+    }
+}
\ No newline at end of file