Fix cache serializer

This commit is contained in:
Laura Hausmann 2024-01-28 02:49:30 +01:00
parent 3e4410f52c
commit f7539b5374
No known key found for this signature in database
GPG key ID: D044E84C5BE01605

View file

@ -6,16 +6,21 @@ namespace Iceshrimp.Backend.Core.Extensions;
public static class DistributedCacheExtensions {
//TODO: named caches, CacheService?
//TODO: thread-safe locks to prevent fetching data more than once
//TODO: sliding window ttl?
public static async Task<T?> Get<T>(this IDistributedCache cache, string key) {
var buffer = await cache.GetAsync(key);
if (buffer == null) return default;
if (buffer == null || buffer.Length == 0) return default;
var stream = new MemoryStream(buffer);
try {
var data = await JsonSerializer.DeserializeAsync<T>(stream);
return data != null ? (T)data : default;
}
catch {
return default;
}
}
public static async Task<T> Fetch<T>(this IDistributedCache cache, string key, TimeSpan ttl,
Func<Task<T>> fetcher) {
@ -28,11 +33,10 @@ public static class DistributedCacheExtensions {
}
public static async Task Set<T>(this IDistributedCache cache, string key, T data, TimeSpan ttl) {
using var ms = new MemoryStream();
await JsonSerializer.SerializeAsync(ms, data);
var buffer = new Memory<byte>();
_ = await ms.ReadAsync(buffer);
using var stream = new MemoryStream();
await JsonSerializer.SerializeAsync(stream, data);
stream.Position = 0;
var options = new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = ttl };
await cache.SetAsync(key, buffer.ToArray(), options);
await cache.SetAsync(key, stream.ToArray(), options);
}
}