[backend/services] Fix multiple threads creating the same user simultaneously, causing postgres duplicate key exceptions

This commit is contained in:
Laura Hausmann 2024-02-12 05:56:28 +01:00
parent 6c955262ee
commit a8f174f02a
No known key found for this signature in database
GPG key ID: D044E84C5BE01605

View file

@ -112,10 +112,21 @@ public class UserService(
KeyPem = actor.PublicKey.PublicKey KeyPem = actor.PublicKey.PublicKey
}; };
await db.AddRangeAsync(user, profile, publicKey); try {
await db.SaveChangesAsync(); await db.AddRangeAsync(user, profile, publicKey);
await db.SaveChangesAsync();
return user;
}
catch (DbUpdateException) {
// another thread got there first, so we need to return the existing user
var res = await db.Users
.IncludeCommonProperties()
.FirstOrDefaultAsync(p => p.UsernameLower == user.UsernameLower && p.Host == user.Host);
return user; // something else must have went wrong, rethrow exception
if (res == null) throw;
return res;
}
} }
public async Task<User> UpdateUserAsync(User user) { public async Task<User> UpdateUserAsync(User user) {