From 8a7bb6bc5a5b0f63781429a61dca27ceca22a6be Mon Sep 17 00:00:00 2001 From: "nicolas.dorier" Date: Wed, 26 Jan 2022 15:09:06 +0900 Subject: [PATCH] Retry SaveChanges if deadlock detected in delete store --- .../Services/Stores/StoreRepository.cs | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/BTCPayServer/Services/Stores/StoreRepository.cs b/BTCPayServer/Services/Stores/StoreRepository.cs index e37a26950..61eeaf438 100644 --- a/BTCPayServer/Services/Stores/StoreRepository.cs +++ b/BTCPayServer/Services/Stores/StoreRepository.cs @@ -328,6 +328,7 @@ namespace BTCPayServer.Services.Stores public async Task DeleteStore(string storeId) { + int retry = 0; using var ctx = _ContextFactory.CreateContext(); if (!ctx.Database.SupportDropForeignKey()) return false; @@ -341,10 +342,25 @@ namespace BTCPayServer.Services.Stores foreach (var w in webhooks) ctx.Webhooks.Remove(w); ctx.Stores.Remove(store); - await ctx.SaveChangesAsync(); + retry: + try + { + await ctx.SaveChangesAsync(); + } + catch (DbUpdateException ex) when (IsDeadlock(ex) && retry < 5) + { + await Task.Delay(100); + retry++; + goto retry; + } return true; } + private static bool IsDeadlock(DbUpdateException ex) + { + return ex.InnerException is Npgsql.PostgresException postgres && postgres.SqlState == "40P01"; + } + public bool CanDeleteStores() { using var ctx = _ContextFactory.CreateContext();