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 { public static class DistributedCacheExtensions {
//TODO: named caches, CacheService? //TODO: named caches, CacheService?
//TODO: thread-safe locks to prevent fetching data more than once //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) { public static async Task<T?> Get<T>(this IDistributedCache cache, string key) {
var buffer = await cache.GetAsync(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); var stream = new MemoryStream(buffer);
try {
var data = await JsonSerializer.DeserializeAsync<T>(stream); var data = await JsonSerializer.DeserializeAsync<T>(stream);
return data != null ? (T)data : default; return data != null ? (T)data : default;
} }
catch {
return default;
}
}
public static async Task<T> Fetch<T>(this IDistributedCache cache, string key, TimeSpan ttl, public static async Task<T> Fetch<T>(this IDistributedCache cache, string key, TimeSpan ttl,
Func<Task<T>> fetcher) { 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) { public static async Task Set<T>(this IDistributedCache cache, string key, T data, TimeSpan ttl) {
using var ms = new MemoryStream(); using var stream = new MemoryStream();
await JsonSerializer.SerializeAsync(ms, data); await JsonSerializer.SerializeAsync(stream, data);
var buffer = new Memory<byte>(); stream.Position = 0;
_ = await ms.ReadAsync(buffer);
var options = new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = ttl }; var options = new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = ttl };
await cache.SetAsync(key, buffer.ToArray(), options); await cache.SetAsync(key, stream.ToArray(), options);
} }
} }