From 6e7c8b20bceadef060e7fd557b26a0fe4ca68ab3 Mon Sep 17 00:00:00 2001 From: "seer-by-sentry[bot]" <157164994+seer-by-sentry[bot]@users.noreply.github.com> Date: Fri, 5 Jun 2026 20:18:12 +0000 Subject: [PATCH] fix(social): Make CreateFriendship idempotent --- GenOnlineService/Database/Database.Social.cs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/GenOnlineService/Database/Database.Social.cs b/GenOnlineService/Database/Database.Social.cs index 887a79c..d60876a 100644 --- a/GenOnlineService/Database/Database.Social.cs +++ b/GenOnlineService/Database/Database.Social.cs @@ -198,6 +198,14 @@ public static async Task CreateFriendship(AppDbContext db, long userId1, long us { try { + // Check if friendship already exists (handles duplicate calls / race conditions) + bool alreadyExists = await db.Friends.AnyAsync(f => + (f.UserId1 == userId1 && f.UserId2 == userId2) || + (f.UserId1 == userId2 && f.UserId2 == userId1)); + + if (alreadyExists) + return; + db.Friends.Add(new FriendEntry { UserId1 = userId1, @@ -208,6 +216,12 @@ public static async Task CreateFriendship(AppDbContext db, long userId1, long us } catch (Exception ex) { + // If two concurrent calls both passed the existence check, MySQL will throw a + // duplicate-key error (ER_DUP_ENTRY, code 1062). The friendship was already + // created by the other call, so this is not an error worth reporting. + if (ex.InnerException is MySqlConnector.MySqlException mysqlEx && mysqlEx.Number == 1062) + return; + Console.WriteLine($"[ERROR] CreateFriendship failed: {ex.Message}"); SentrySdk.CaptureException(ex); }