Skip to content

Commit d272e04

Browse files
committed
2 parents 59d6cb3 + d2ccad8 commit d272e04

1 file changed

Lines changed: 14 additions & 0 deletions

File tree

GenOnlineService/Database/Database.Social.cs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,14 @@ public static async Task CreateFriendship(AppDbContext db, long userId1, long us
198198
{
199199
try
200200
{
201+
// Check if friendship already exists (handles duplicate calls / race conditions)
202+
bool alreadyExists = await db.Friends.AnyAsync(f =>
203+
(f.UserId1 == userId1 && f.UserId2 == userId2) ||
204+
(f.UserId1 == userId2 && f.UserId2 == userId1));
205+
206+
if (alreadyExists)
207+
return;
208+
201209
db.Friends.Add(new FriendEntry
202210
{
203211
UserId1 = userId1,
@@ -208,6 +216,12 @@ public static async Task CreateFriendship(AppDbContext db, long userId1, long us
208216
}
209217
catch (Exception ex)
210218
{
219+
// If two concurrent calls both passed the existence check, MySQL will throw a
220+
// duplicate-key error (ER_DUP_ENTRY, code 1062). The friendship was already
221+
// created by the other call, so this is not an error worth reporting.
222+
if (ex.InnerException is MySqlConnector.MySqlException mysqlEx && mysqlEx.Number == 1062)
223+
return;
224+
211225
Console.WriteLine($"[ERROR] CreateFriendship failed: {ex.Message}");
212226
SentrySdk.CaptureException(ex);
213227
}

0 commit comments

Comments
 (0)