From f7539b5374a80ad5ebfd93dfa6aa22c8c7e76732 Mon Sep 17 00:00:00 2001 From: Laura Hausmann Date: Sun, 28 Jan 2024 02:49:30 +0100 Subject: [PATCH] Fix cache serializer --- .../Extensions/DistributedCacheExtensions.cs | 22 +++++++++++-------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/Iceshrimp.Backend/Core/Extensions/DistributedCacheExtensions.cs b/Iceshrimp.Backend/Core/Extensions/DistributedCacheExtensions.cs index a3dd6bde..29b7defd 100644 --- a/Iceshrimp.Backend/Core/Extensions/DistributedCacheExtensions.cs +++ b/Iceshrimp.Backend/Core/Extensions/DistributedCacheExtensions.cs @@ -6,15 +6,20 @@ 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 Get(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); - var data = await JsonSerializer.DeserializeAsync(stream); - - return data != null ? (T)data : default; + try { + var data = await JsonSerializer.DeserializeAsync(stream); + return data != null ? (T)data : default; + } + catch { + return default; + } } public static async Task Fetch(this IDistributedCache cache, string key, TimeSpan ttl, @@ -28,11 +33,10 @@ public static class DistributedCacheExtensions { } public static async Task Set(this IDistributedCache cache, string key, T data, TimeSpan ttl) { - using var ms = new MemoryStream(); - await JsonSerializer.SerializeAsync(ms, data); - var buffer = new Memory(); - _ = 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); } } \ No newline at end of file