From 7e89c0e4c40917a8963cc180588f644c5fca27ff Mon Sep 17 00:00:00 2001 From: Laura Hausmann Date: Sat, 23 Mar 2024 19:02:12 +0100 Subject: [PATCH] [backend/core] Use upsert for cache store instead of detecting conflicts (ISH-212) --- .../Core/Services/CacheService.cs | 25 ++++++++----------- Iceshrimp.Backend/Iceshrimp.Backend.csproj | 1 + 2 files changed, 11 insertions(+), 15 deletions(-) diff --git a/Iceshrimp.Backend/Core/Services/CacheService.cs b/Iceshrimp.Backend/Core/Services/CacheService.cs index 3dec1e8f..138d1b06 100644 --- a/Iceshrimp.Backend/Core/Services/CacheService.cs +++ b/Iceshrimp.Backend/Core/Services/CacheService.cs @@ -147,21 +147,16 @@ public class CacheService([FromKeyedServices("cache")] DatabaseContext db) Expiry = expiry, Ttl = ttl }; - db.Add(entity); - try - { - await db.SaveChangesAsync(); - } - catch (UniqueConstraintException) - { - db.Remove(entity); - entity = await db.CacheStore.FirstOrDefaultAsync(p => p.Key == key) ?? - throw new Exception("Failed to fetch entity after UniqueConstraintException"); - entity.Value = value; - entity.Expiry = expiry; - entity.Ttl = ttl; - await db.SaveChangesAsync(); - } + + await db.CacheStore.Upsert(entity) + .On(p => p.Key) + .WhenMatched((_, orig) => new CacheEntry + { + Value = orig.Value, + Expiry = orig.Expiry, + Ttl = orig.Ttl + }) + .RunAsync(); } } diff --git a/Iceshrimp.Backend/Iceshrimp.Backend.csproj b/Iceshrimp.Backend/Iceshrimp.Backend.csproj index 6c84bf8e..60b77ef3 100644 --- a/Iceshrimp.Backend/Iceshrimp.Backend.csproj +++ b/Iceshrimp.Backend/Iceshrimp.Backend.csproj @@ -25,6 +25,7 @@ +