Skip to content

Optimize find_primary_user_by_scoped_user_id method for better performance

Everyone can contribute. Help move this issue forward while earning points, leveling up and collecting rewards.

Summary

This is a followup issue from !204010 (merged) based on a review comment by @fabiopitino.

The current implementation of Gitlab::Auth::Identity.find_primary_user_by_scoped_user_id may be CPU heavy when executed constantly and handles too many internal implementation details rather than relying on existing abstractions.

Current Implementation

def self.find_primary_user_by_scoped_user_id(scoped_user_id, store: ::Gitlab::SafeRequestStore)
  return unless scoped_user_id

  # Get all composite identities from the store
  composite_identities = store.store[COMPOSITE_IDENTITY_USERS_KEY] || Set.new

  # Check each composite identity to find the one with matching scoped user
  composite_identities.find do |primary_user|
    identity_key = format(COMPOSITE_IDENTITY_KEY_FORMAT, primary_user.id)
    scoped_user = store.store[identity_key]

    scoped_user&.id == scoped_user_id
  end
end

Proposed Optimization

def self.find_primary_user_by_scoped_user_id(scoped_user_id)
  return unless scoped_user_id
  identity = currently_linked

  identity.primary_user if identity.linked? && identity&.scoped_user.id == scoped_user_id
end

Benefits

  1. Performance: Reduces CPU overhead by leveraging existing abstractions
  2. Maintainability: Less handling of internal implementation details
  3. Consistency: Uses established patterns in the codebase

Additional Notes

  • The variable name composite_identities should be renamed to primary_users for clarity
  • This optimization should maintain the same functionality while improving performance

References

Edited by 🤖 GitLab Bot 🤖