[management] reduce calls to update last usage for users and pats (#8290)

This commit is contained in:
Pascal Fischer
2026-10-22 19:13:11 +02:00
committed by GitHub
parent c476196653
commit 431e201355
8 changed files with 178 additions and 27 deletions
+23 -11
View File
@@ -252,20 +252,32 @@ func (s *SqlStore) GetAccountIDByUserID(ctx context.Context, lockStrength Lockin
return accountID, nil
}
// SaveUserLastLogin stores the last login time for a user in DB.
// SaveUserLastLogin stores the last login time for a user in DB. It only writes when the stored value is unset or
// older than lastLogin, so repeating the same login doesn't rewrite the row and an older login never overwrites a newer one.
// It returns a NotFound error when the user doesn't exist.
func (s *SqlStore) SaveUserLastLogin(ctx context.Context, accountID, userID string, lastLogin time.Time) error {
var user types.User
result := s.db.Take(&user, accountAndIDQueryCondition, accountID, userID)
if result.Error != nil {
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
return status.NewUserNotFoundError(userID)
}
return status.NewGetUserFromStoreError()
if lastLogin.IsZero() {
return nil
}
if !lastLogin.IsZero() {
user.LastLogin = &lastLogin
return s.db.Save(&user).Error
result := s.db.Model(&types.User{}).
Where(accountAndIDQueryCondition, accountID, userID).
Where("last_login IS NULL OR last_login < ?", lastLogin).
Update("last_login", lastLogin)
if result.Error != nil {
log.WithContext(ctx).Errorf("failed to save user last login: %s", result.Error)
return status.Errorf(status.Internal, "failed to save user last login")
}
if result.RowsAffected == 0 {
var count int64
if err := s.db.Model(&types.User{}).Where(accountAndIDQueryCondition, accountID, userID).Count(&count).Error; err != nil {
log.WithContext(ctx).Errorf("failed to check user existence: %s", err)
return status.NewGetUserFromStoreError()
}
if count == 0 {
return status.NewUserNotFoundError(userID)
}
}
return nil