[backend/services] Fix multiple threads creating the same user simultaneously, causing postgres duplicate key exceptions
This commit is contained in:
parent
6c955262ee
commit
a8f174f02a
1 changed files with 14 additions and 3 deletions
|
@ -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;
|
||||||
|
|
Loading…
Add table
Reference in a new issue