module Gitlab
  module PerformanceBar
    include Gitlab::CurrentSettings

    ALLOWED_USER_IDS_KEY = 'performance_bar_allowed_user_ids'.freeze

    def self.enabled?(user = nil)
      return false unless user && allowed_group_id

      allowed_user_ids.include?(user.id)
    end

    def self.allowed_group_id
      current_application_settings.performance_bar_allowed_group_id
    end

    def self.allowed_user_ids
      Rails.cache.fetch(ALLOWED_USER_IDS_KEY) do
        group = Group.find_by_id(allowed_group_id)

        if group
          GroupMembersFinder.new(group).execute.pluck(:user_id)
        else
          []
        end
      end
    end

    def self.expire_allowed_user_ids_cache
      Rails.cache.delete(ALLOWED_USER_IDS_KEY)
    end
  end
end

module Gitlab
  module PerformanceBar
    include Gitlab::CurrentSettings

    ALLOWED_USER_IDS_KEY = 'performance_bar_allowed_user_ids:v2'.freeze
    EXPIRY_TIME = 5.minutes

    def self.enabled?(user = nil)
      return false unless user && allowed_group_id

      allowed_user_ids.include?(user.id)
    end

    def self.allowed_group_id
      current_application_settings.performance_bar_allowed_group_id
    end

    def self.allowed_user_ids
      Rails.cache.fetch(ALLOWED_USER_IDS_KEY, expires_in: EXPIRY_TIME) do
        group = Group.find_by_id(allowed_group_id)

        if group
          GroupMembersFinder.new(group).execute.pluck(:user_id)
        else
          []
        end
      end
    end

    def self.expire_allowed_user_ids_cache
      Rails.cache.delete(ALLOWED_USER_IDS_KEY)
    end
  end
end

Expire cached user IDs that can see the performance after 5 minutes
Expire cached user IDs that can see the performance after 5 minutes

If we don't expire the cached user IDs, the list of IDs would become
outdated when a new member is added, or when a member ios removed from
the allowed group.

Signed-off-by: Rémy Coutable <4ea0184b9df19e0786dd00b28e6daa4d26baeb3e@rymai.me>
