[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,11 +112,22 @@ public class UserService(
KeyPem = actor.PublicKey.PublicKey KeyPem = actor.PublicKey.PublicKey
}; };
try {
await db.AddRangeAsync(user, profile, publicKey); await db.AddRangeAsync(user, profile, publicKey);
await db.SaveChangesAsync(); await db.SaveChangesAsync();
return user; 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);
// 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) {
if (!user.NeedsUpdate) return user; if (!user.NeedsUpdate) return user;