From 00ac76cc4ce87954d770abae411c54eb8bf23360 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9my=20Coutable?= Date: Tue, 4 Jul 2017 16:15:24 +0200 Subject: Cache the allowed user IDs for the performance bar, in Redis for 10 minutes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Rémy Coutable --- lib/gitlab/performance_bar.rb | 52 +++++++++++++++++++++++++++++-------------- 1 file changed, 35 insertions(+), 17 deletions(-) (limited to 'lib/gitlab/performance_bar.rb') diff --git a/lib/gitlab/performance_bar.rb b/lib/gitlab/performance_bar.rb index 60c8ba5063e..85f4371ec23 100644 --- a/lib/gitlab/performance_bar.rb +++ b/lib/gitlab/performance_bar.rb @@ -1,35 +1,53 @@ module Gitlab module PerformanceBar + ALLOWED_USER_IDS_KEY = 'performance_bar_allowed_user_ids'.freeze + # The time (in seconds) after which a set of allowed user IDs is expired + # automatically. + ALLOWED_USER_IDS_TIME_TO_LIVE = 10.minutes.to_i + def self.enabled?(current_user = nil) Feature.enabled?(:gitlab_performance_bar, current_user) end def self.allowed_user?(user) - return false unless allowed_group + return false unless allowed_group_name - if RequestStore.active? - RequestStore.fetch('performance_bar:user_member_of_allowed_group') do - user_member_of_allowed_group?(user) - end - else - user_member_of_allowed_group?(user) - end + allowed_user_ids.include?(user.id) end - def self.allowed_group - return nil unless Gitlab.config.performance_bar.allowed_group + def self.allowed_group_name + Gitlab.config.performance_bar.allowed_group + end + + def self.allowed_user_ids + Gitlab::Redis.with do |redis| + if redis.exists(cache_key) + redis.smembers(cache_key).map(&:to_i) + else + group = Group.find_by_full_path(allowed_group_name) + # Redis#sadd doesn't accept an empty array, but we still want to use + # Redis to let us know that no users are allowed, so we set the + # array to [-1] in this case. + user_ids = + if group + GroupMembersFinder.new(group).execute + .pluck(:user_id).presence || [-1] + else + [-1] + end + + redis.multi do + redis.sadd(cache_key, user_ids) + redis.expire(cache_key, ALLOWED_USER_IDS_TIME_TO_LIVE) + end - if RequestStore.active? - RequestStore.fetch('performance_bar:allowed_group') do - Group.find_by_full_path(Gitlab.config.performance_bar.allowed_group) + user_ids end - else - Group.find_by_full_path(Gitlab.config.performance_bar.allowed_group) end end - def self.user_member_of_allowed_group?(user) - GroupMembersFinder.new(allowed_group).execute.exists?(user_id: user.id) + def self.cache_key + "#{ALLOWED_USER_IDS_KEY}:#{allowed_group_name}" end end end -- cgit v1.2.3