summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAndreas Brandl <abrandl@gitlab.com>2018-02-23 20:56:43 +0100
committerAndreas Brandl <abrandl@gitlab.com>2018-03-06 12:53:13 +0100
commitd4d0740e24315e7071f90b3744377b3ca3b5816a (patch)
treef8f2e6cc95617808db683c6e26aad9e251140547
parentebcf3c73bd515a4884961999ef7d33edaba93d57 (diff)
downloadgitlab-ce-d4d0740e24315e7071f90b3744377b3ca3b5816a.tar.gz
Cache project/user combinations.
-rw-r--r--app/models/user_contributed_projects.rb22
-rw-r--r--spec/models/user_contributed_projects_spec.rb7
2 files changed, 23 insertions, 6 deletions
diff --git a/app/models/user_contributed_projects.rb b/app/models/user_contributed_projects.rb
index 846d77f3c69..e051e75af1d 100644
--- a/app/models/user_contributed_projects.rb
+++ b/app/models/user_contributed_projects.rb
@@ -5,9 +5,25 @@ class UserContributedProjects < ActiveRecord::Base
validates :project, presence: true
validates :user, presence: true
+ CACHE_EXPIRY_TIME = 1.day
+
def self.track(event)
- find_or_create_by!(project: event.project, user: event.author)
- rescue ActiveRecord::RecordNotUnique
- retry
+ attributes = {project_id: event.project_id, user_id: event.author_id}
+
+ cached_exists?(attributes) do
+ begin
+ find_or_create_by!(attributes)
+ true # not caching the whole record here for now
+ rescue ActiveRecord::RecordNotUnique
+ retry
+ end
+ end
+ end
+
+ private
+
+ def self.cached_exists?(project_id:, user_id:, &block)
+ cache_key = "user_contributed_projects:#{project_id}:#{user_id}"
+ Rails.cache.fetch(cache_key, expires_in: CACHE_EXPIRY_TIME, &block)
end
end
diff --git a/spec/models/user_contributed_projects_spec.rb b/spec/models/user_contributed_projects_spec.rb
index 5b8c61750b3..b0a10ca59ab 100644
--- a/spec/models/user_contributed_projects_spec.rb
+++ b/spec/models/user_contributed_projects_spec.rb
@@ -12,16 +12,17 @@ describe UserContributedProjects do
it 'creates a record' do
expect { subject }.to change { UserContributedProjects.count }.from(0).to(1)
end
-
end
end
it 'sets project accordingly' do
- expect(subject.project).to eq(event.project)
+ subject
+ expect(UserContributedProjects.first.project).to eq(event.project)
end
it 'sets user accordingly' do
- expect(subject.user).to eq(event.author)
+ subject
+ expect(UserContributedProjects.first.user).to eq(event.author)
end
it 'only creates a record once per user/project' do