From 096375344ef87fe53ca009b7a7eaa34c9c9f5407 Mon Sep 17 00:00:00 2001 From: Rory& Date: Fri, 15 Mar 2024 18:10:58 +0100 Subject: Bot changes, move named filters to subclass --- .../Extensions/NamedCaches/NamedCache.cs | 37 ++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 LibMatrix/Homeservers/Extensions/NamedCaches/NamedCache.cs (limited to 'LibMatrix/Homeservers/Extensions/NamedCaches/NamedCache.cs') 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(AuthenticatedHomeserverGeneric hs, string name) where T : class { + private Dictionary? _cache = new(); + private DateTime _expiry = DateTime.MinValue; + + public async Task> ReadCacheMapAsync() { + _cache = await hs.GetAccountDataOrNullAsync>(name); + + return _cache ?? new(); + } + + public async Task> ReadCacheMapCachedAsync() { + if (_expiry < DateTime.Now || _cache == null) { + _cache = await ReadCacheMapAsync(); + _expiry = DateTime.Now.AddMinutes(5); + } + + return _cache; + } + + public virtual async Task GetValueAsync(string key) { + return (await ReadCacheMapCachedAsync()).GetValueOrDefault(key); + } + + public virtual async Task SetValueAsync(string key, T value) { + var cache = await ReadCacheMapCachedAsync(); + cache[key] = value; + await hs.SetAccountDataAsync(name, cache); + + return value; + } + + public virtual async Task GetOrSetValueAsync(string key, Func> value) { + return (await ReadCacheMapCachedAsync()).GetValueOrDefault(key) ?? await SetValueAsync(key, await value()); + } +} \ No newline at end of file -- cgit 1.4.1